首页 > 代码库 > js实现复选框的全选、全不选、反选

js实现复选框的全选、全不选、反选

 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="http://www.mamicode.com/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="http://www.mamicode.com/下棋"/>下棋</br><input type="checkbox" name="inter" value="http://www.mamicode.com/游戏"/>游戏</br><input type="checkbox" name="inter" value="http://www.mamicode.com/看书"/>看书<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="http://www.mamicode.com/下棋"/>下棋<br/><input type="checkbox" name="inter" value="http://www.mamicode.com/游戏"/>游戏<br/><input type="checkbox" name="inter" value="http://www.mamicode.com/看书"/>看书<br/><input type="button" onclick="checkall()" value="http://www.mamicode.com/全选"/><input type="button" onclick="checkall(‘un‘)" value="http://www.mamicode.com/全不选"/><input type="button" onclick="uncheck()" value="http://www.mamicode.com/反选"/></body></html>

 

   

js实现复选框的全选、全不选、反选