全选和反选的操作思路如下:
首先获得全选反选框的状态值。
其次将所有的多选框加入列表 可以根据标签 可以根据 ID name 还可以根据 class 等等方式 形成数组
最后 循环 设置每个多选框的值 = 全选 / 反选框的状态值。
我的写法如下。
<?php
header("content-type:text/html;charset=utf8");
?>
<html>
<head>
<title> 内容多选测试 </title>
</head>
<body>
<form name="duoxuan" action="duoxuan.php?act=delete">
<div>
<dl>
<?php
for ($i = 0; $i < 10; $i++) {
?>
<dd> 第 <?php echo $i + 1; ?> 个多选框:<input name="dxk" type="checkbox"></dd>
<?php
}
?>
<dd> 全选 <input type="checkbox" name="chkall" id="all" onclick="xuan(this.checked)"></dd>
</dl>
<dl>
<dd>
<button type="submit" value="提交"> 提交 </button>
</dd>
</dl>
<script>
function xuan(e) {var a = document.getElementsByName('dxk');
for (var i = 0; i < a.length; i++) {a[i].checked = e;
}
}
</script>
</div>
</form>
</body>
</html>
网上找了两个写法如下。
第二个写法和我的思路基本一样
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" id="checkbox" value="1" onclick="check()" /> 全选 / 反选 <br />
<input type="checkbox" value="${article.id}" name="box" class="item" /> 奶茶 <br />
<input type="checkbox" value="${article.id}" name="box" class="item"/> 香蕉 <br />
<input type="checkbox" value="${article.id}" name="box" class="item"/> 橘子 <br />
<input type="checkbox" value="${article.id}" name="box" class="item"/> 苹果 <br />
<input type="checkbox" value="${article.id}" name="box" class="item"/> 梨子 <br />
<script type="text/javascript">
function quanxuan(){var $checkbox = $(".item");
var $checked = $checkbox.filter(":checked");
if($checkbox.length == $checked.length){$("#checkbox").prop("checked",true);
}else{$("#checkbox").prop("checked",false);
}
}
$(function(){$("#checkbox").on("change",function(){var checked = $(this).prop("checked"); // true / false
$(".item").prop("checked",checked);
quanxuan();});
$("body").on("change" , ".item",function(e){quanxuan();
});
});
</script>
</body>
</html>
第二种纯粹的 js 写法
<html>
<meta charset="UTF-8">
<head>
<title> 复选框 checked 属性 </title>
<script language="JavaScript" type="text/javascript">
function changeState(isChecked)
{var chk_list=document.getElementsByTagName("input");
for(var i=0;i<chk_list.length;i++)
{if(chk_list[i].type=="checkbox")
{chk_list[i].checked=isChecked;
}
}
}
</script>
</head>
<body>
<h1> 请选择你的爱好 </h1>
<form name="myForm1">
<input type="checkbox" name="cb1" checked> 看书 <br>
<input type="checkbox" name="cb2" checked> 上网 <br>
<input type="checkbox" name="cb3"> 游戏 <br>
</form>
<hr>
<form name="myForm2">
<input type="checkbox" name="cb" onclick="changeState(this.checked)"> 全选
</form> </body>
</html>
正文完