checkbox的全选、取消全选、选中所有奇数、选中所有偶数等方法的实现代码如下:
注意jQuery的版本:jQuery1.6增加了prop,1.6之前的还是使用attr()和removeAttr()
<!DOCTYPE html>
<html lang="en">
<head> <title>checkbox全选、反选等实现方式</title> <meta charset="UTF-8"><script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script><script type="text/javascript"> $(function($){//prop是jQuery1.6新增的,jQuery1.6之前还是用attr和removeAttr。//全选 $("#btn1").click(function(){ // alert('选中1!');// $("input[name='checkbox']").attr("checked","true");$("input[name='checkbox']").prop("checked",true); });//取消全选$("#btn2").click(function(){ // alert('选中2!');// $("input[name='checkbox']").removeAttr("checked"); $("input[name='checkbox']").prop("checked", false); });//选中所有奇数 $("#btn3").click(function(){// alert('选中3!');// $("input[name='checkbox']:even").attr("checked","true");$("input[name='checkbox']").prop("checked", false); $("input[name='checkbox']:even").prop("checked", true); });//选中所有偶数 $("#btn6").click(function(){ // alert('选中4!');// $("input[name='checkbox']:odd").attr("checked","true"); $("input[name='checkbox']").prop("checked", false); $("input[name='checkbox']:odd").prop("checked", true); });//反选-jQuery1.5/*$("#btn4").click(function(){ $("input[name='checkbox']").each(function(){ if($(this).attr("checked")) { $(this).removeAttr("checked"); }else { $(this).attr("checked","true"); } });}) *///反选-jQuery1.6$("#btn4").click(function(){ $("input[type='checkbox']").prop("checked", function( i, val ) { //i:索引 val:true/false(选中为true,否则为false)return !val;});})//获取选择项的值 var aa=""; $("#btn5").click(function(){ $("input[name='checkbox']:checkbox:checked").each(function(){ aa+=$(this).val();});document.write(aa); });})</script>
</head>
<body> <form id="form1" runat="server"> <div> <input type="button" id="btn1" value="全选"><input type="button" id="btn2" value="取消全选"> <input type="button" id="btn3" value="选中所有奇数"> <input type="button" id="btn6" value="选中所有偶数"> <input type="button" id="btn4" value="反选"> <input type="button" id="btn5" value="获得选中的所有值"> <br><input type="checkbox" name="checkbox" value="checkbox1">checkbox1<br><input type="checkbox" name="checkbox" value="checkbox2">checkbox2<br><input type="checkbox" name="checkbox" value="checkbox3">checkbox3<br><input type="checkbox" name="checkbox" value="checkbox4">checkbox4<br><input type="checkbox" name="checkbox" value="checkbox5">checkbox5<br><input type="checkbox" name="checkbox" value="checkbox6">checkbox6<br><input type="checkbox" name="checkbox" value="checkbox7">checkbox7<br><input type="checkbox" name="checkbox" value="checkbox8">checkbox8</div> </form>
</body>
</html>
注意:禁用复选框的方法:$(“input[type=‘checkbox’]”).prop(“disabled”, true);