用JavaScript实现复选框的全选/全不选效果

判断复选框是否被选中的属性是checked,如果checked属性的值为true,则说明复选框已选中,如果checked属性的值为false,则说明复选框未被选中,可以先将每个复选框的name设置为同名,然后使用getElementsByName()方法访问所有同名的复选框,最后使用循环语句来统一设置所有复选框的checked属性,从而实现全选/全不选效果

示例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
 function check(){
	 var oInput=document.getElementsByName("product");
	 for(var i=0;i<oInput.length;i++){
		 oInput[i].checked=document.getElementById("all").checked;
	 }
	 
 }
 
 
 
 
</script>
</head>
<body>
<table border="0" cellspacing="0" class="bg">
        <td><input id="all" type="checkbox" value="全选" onclick="check()"/>全选</td>
         <td>商品图片</td>
         <td>商品名称</td>
         <td>商品价格</td>
         <tr>
         <td><input name="product" type ="checkbox" value="1"/></td>
         <tr>
         <td><input name="product" type ="checkbox" value="2"/></td>
         <tr>
         <td><input name="product" type ="checkbox" value="3"/></td>
         <tr>
         <td><input name="product" type ="checkbox" value="4"/></td>
</table>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_37774171/article/details/86583574