jQuery 实现复选框多选
页面代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <!DOCTYPE html> <html> <head> <title>全选和反选</title> </head> <body> <input type="checkbox" name="chkFirst" /><br /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> <input type="checkbox" name="chkSec" /> </body> </html>
|
jQuery 代码,自行加载一个 jQuery 到该页面中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var chkFirst = $('input[name="chkFirst"]'); var chkSec = $('input[name="chkSec"]'); chkFirst.click(function() { chkSec.prop("checked", $(this).is(":checked")); }); var len = chkSec.length; chkSec.click(function() { chkFirst.prop( "checked", $('input[name="chkSec"]:checked').length == len ? true : false ); });
|
JavaScript 实现复选框多选
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 37 38 39 40 41 42 43
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>全选、反选</title> </head> <body> <form> <input type="checkbox" name="" id="all" onclick="selectAll();" />全选<br /> <hr /> <br /> <input class="chk" type="checkbox" name="chk" onclick="selectSingle();" />菜单一<br /><br /> <input class="chk" type="checkbox" name="chk" onclick="selectSingle();" />菜单二<br /><br /> <input class="chk" type="checkbox" name="chk" onclick="selectSingle();" />菜单三<br /><br /> <input class="chk" type="checkbox" name="chk" onclick="selectSingle();" />菜单四<br /><br /> </form> </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
| <script type="text/javascript" > var dom=document.getElementById('all'); var doms=document.getElementsByName('chk'); function selectAll(){ var len = doms.length; for(var i=0;i<len;i++){ if(dom.checked){ doms[i].checked=true; }else{ doms[i].checked=false; }}}; function selectSingle(){ let len = 0; let count = doms.length; for(var i=0;i<count;i++){ if(doms[i].checked==true){ len++; }} if (count == len) { dom.checked = true; }else{ dom.checked = false; }} </script>
|