jQuery实现CheckBox全选、反选、全不选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery实现CheckBox全选、全不选</title>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#checkAll").click(function() {
$('input[name="subBox"]').attr("checked", this.checked);
});
var $subBox = $("input[name='subBox']");
$subBox.click(function() {
$("#checkAll").attr("checked", $subBox.length == $("input[name='subBox']:checked").length ? true: false);
});
});
</script>

</head>
<body>
<div>
<input id="checkAll" type="checkbox" />全选
<input name="subBox" type="checkbox" />项1
<input name="subBox" type="checkbox" />项2
<input name="subBox" type="checkbox" />项3
<input name="subBox" type="checkbox" />项4
</div>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>全选,不全选,反选</title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
$("#selectAll").click(function () {//全选
$("#playList :checkbox").prop("checked", true);
});

$("#unSelect").click(function () {//全不选
$("#playList :checkbox").prop("checked", false);
});

$("#reverse").click(function () {//反选
$("#playList :checkbox").each(function () {
$(this).prop("checked", !$(this).prop("checked"));
});
});
});
</script>
</head>
<body>
<div id="playList">
<input type="checkbox" value="歌曲1" />歌曲1<br />
<input type="checkbox" value="歌曲2" />歌曲2<br />
<input type="checkbox" value="歌曲3" />歌曲3<br />
<input type="checkbox" value="歌曲4" />歌曲4<br />
<input type="checkbox" value="歌曲5" />歌曲5<br />
<input type="checkbox" value="歌曲6" />歌曲6
</div>
<input type="button" value="全选" id="selectAll" />
<input type="button" value="全不选" id="unSelect" />
<input type="button" value="反选" id="reverse" />
</body>
</html>

注:JQuery1.9以上版本,全选/反选功能实现,建议将attr属性换成prop,否则:第一次页面加载全选是可以,取消几个不选,再点【全选】就没有效果。