---
title: "Jquery实现checkbox全选、反选、取消选择、判断是否选择"
author: "xingsan_zhang"
date: "2014-11-13T17:05:30Z"
tags: []
categories: ["Web前端"]
slug: "jquery-checkbox"
draft: false
lastmod: "2014-11-13T17:05:30Z"
id: 2155605
url: "https://uuider.iteye.com/blog/2155605"
---

记录点滴，从小做起！

 

今天，工作中写到关于复选框的操作处理，记录下来。

下面是网上的例子：

 

页面代码：

```
 <a href="javascript:;" id="all">全部选择</a><br>
 <a href="javascript:;" id="delAll">取消选择</a><br>
 <a href="javascript:;" id="antiAll">反向选择</a>    
  
 <p><input type="checkbox" name="checkbox1">A
 <input type="checkbox" name="checkbox1"> B
 <input type="checkbox" name="checkbox1">C</p>

 <p><input type="checkbox" name="checkbox1">D
 <input type="checkbox" name="checkbox1">E
 <input type="checkbox" name="checkbox1">F</p>
```

 

1.全部选择

```
 $("#all").click(function(){  
  $("input[name='checkbox1']").each(function(){
   $(this).attr("checked",true);
  });  
 });
```

 

2.取消选择

```
$("#delAll").click(function(){  
  $("input[name='checkbox1']").each(function(){
   $(this).attr("checked",false);
  });  
 });
```

 

3.反向选择

```
$("#antiAll").click(function(){
  $("input[name='checkbox1']").each(function(){
   $(this).attr("checked",!this.checked);              
});
```

 

4.再写一个判断是否选择

```
var flag=false;
$("input[name='fruit']:checkbox").each(function(){
    if($(this).attr('checked')){
        flag=true;
    }
})
if(flag){
    alert('有被选中');
}else{
    alert('没有选中任何选项');
}
```

 

参考文章：http://blog.sina.com.cn/s/blog\_5a08b1780100duqx.html