js中实现复选框的全选,全不选以及反选,分为两种情况:
(1)选中“请选择”前面的复选框实现全选,不选中“请选择”前面的复选框实现全不选
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <script type="text/javascript" src="jquery-1.9.1.js"></script> <title>无标题文档</title> </head> <script> function check_inter(){ var inters = document.getElementsByName("inter"); for(var i=0;i<inters.length;i++){ if(document.getElementById("cbox").checked==true){ inters[i].checked = true; }else{ inters[i].checked = false; } } } </script> <body> <input type="checkbox" id="cbox" value="" onclick="check_inter()"/>请选择</br> <input type="checkbox" name="inter" value="下棋"/>下棋</br> <input type="checkbox" name="inter" value="游戏"/>游戏</br> <input type="checkbox" name="inter" value="看书"/>看书<br/> </body> </html>
(2)全选、全不选、反选三个按钮实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> </head> <script> //全选,全不选 function checkall(param){ var inters = document.getElementsByName("inter"); for(var i=0;i<inters.length;i++){ if(!param){ inters[i].checked = true; }else{ inters[i].checked = false; } } } //反选 function uncheck(){ var inters = document.getElementsByName("inter"); for(var i=0;i<inters.length;i++){ inters[i].checked = !inters[i].checked; } } </script> <body> <input type="checkbox" name="inter" value="下棋"/>下棋<br/> <input type="checkbox" name="inter" value="游戏"/>游戏<br/> <input type="checkbox" name="inter" value="看书"/>看书<br/> <input type="button" onclick="checkall()" value="全选"/> <input type="button" onclick="checkall(‘un‘)" value="全不选"/> <input type="button" onclick="uncheck()" value="反选"/> </body> </html>
时间: 2024-12-13 14:24:58