<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Jquery 全选/反选</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div>
选择你喜欢的编程语言:<p/>
<label><input type="checkbox" name="ck_all" id="ck_all" value="全选/反选"/>全选/反选</label>
<label><input type="button" id="btn" name="btn" value="获取选中checkbox值"/></label><br/>
<label><input type="checkbox" name="ck_ids" value="C#" />C#</label>
<label> <input type="checkbox" name="ck_ids" value="Java"/>Java</label>
<label> <input type="checkbox" name="ck_ids" value="C"/>C</label>
<label> <input type="checkbox" name="ck_ids" value="Python"/>Python</label>
</div>
<script>
$(document).ready(function(){
//全选/反选
$("#ck_all").click(function(){
$("input[name='ck_ids']").each(function(){
if (this.checked) {
this.checked = false;
}
else {
this.checked = true;
}
});
});
//子项click事件,处理全选/反选状态
$("input[name='ck_ids']").click(function(){
if($("input[name='ck_ids']:checked").length==$("input[name='ck_ids']").length){
$("#ck_all").prop("checked",true);
}else{
$("#ck_all").prop("checked",false);
}
});
//获取选中值
$("#btn").click(function(){
var ids ='';
$("input[name='ck_ids']:checked").each(function () {
ids ? (ids += ','+$(this).val()):ids+=$(this).val();
});
alert(ids);
return ids;
});
//获取选中值(另一种方式)
function getValues(){
var arr = new Array();
$("input[name='ck_ids']:checked").each(function () {
arr.push($(this).val());
});
var vus = arr.join(",");
return vus;
}
});
</script>
</body>
</html>
效果: