要充分考虑各种可能的情况,值得练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>new all select</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
//全不选
function not() {
$(":checkbox").prop("checked",false);
}
//当有一个按钮未选时,全选框不能勾选
function tset_all_ture(checkbox) {
let length = $(":checkbox[name='motion']:checked").length;//被选择的个数
let length1 = $(":checkbox[name='motion']").length;//运动栏目个数
if (checkbox.checked==false){
$("#not_and_all").prop("checked",false);
}
//当手动完成全选时
else if(length==length1){
$("#not_and_all").prop("checked",true);
}
}
//全选
function all() {
let $checkbox = $(":checkbox");
for (const $checkbox1 of $checkbox) {
$checkbox1.checked=true;
}
}
//页面加载完成后要执行的代码
$(function () {
//全选或全不选的复选框
let all_not = $("#not_and_all");
//添加注册事件
all_not.click(function () {
//被选中时,全选
if(all_not.prop("checked")){
//获取id为运动d阿表单项
// let $motion = $(":checkbox");
// $motion.val(["zuqiu","lanqiu","yumaoqiu","pingpangqiu","not/all_select"]);
all();
}
//未勾选时,全不选
else {
not();
}
})
//全选按钮
$("#all").click(function () {
all();
})
//全不选按钮
$("#not").click(function () {
not();
})
//反选按钮
$("#reverse").click(function () {
let $checkbox = $(":checkbox[name='motion']");//获取运动栏目的复选框
var i=0,k=0;
for (const $checkbox1 of $checkbox) {
if ($checkbox1.checked==true){
$checkbox1.checked=false;
i++;
}
else {
$checkbox1.checked=true;
k++;
}
}
//满选时,选定满选框
if (k==$checkbox.length){
$("#not_and_all").prop("checked",true);
}
//非满选时
else {
$("#not_and_all").prop("checked",false);
}
})
//提交按钮
})
</script>
</head>
<body>
<form action="http://localhost:8080" method="get">
<table>
<tr>
<th colspan="2">你爱好的运动是?</th>
<th colspan="2"><input name="not_and_all" id="not_and_all" type="checkbox" value="not/all_select">全选/全不选</th>
</tr>
<tr>
<th><input type="checkbox" id="motion" name="motion" value="zuqiu" onclick="tset_all_ture(this)">足球</th>
<th><input type="checkbox" id="motion" name="motion" value="lanqiu" onclick="tset_all_ture(this)">篮球</th>
<th><input type="checkbox" id="motion" name="motion" value="yumaoqiu" onclick="tset_all_ture(this)">羽毛球</th>
<th><input type="checkbox" id="motion" name="motion" value="pingpangqiu" onclick="tset_all_ture(this)">乒乓球</th>
</tr>
<tr>
<th><button type="button" id="all">全选</button></th>
<th><button type="button" id="not">全不选</button></th>
<th><button type="button" id="reverse">反选</button></th>
<th><button type="submit" id="submit">提交</button></th>
</tr>
</table>
</form>
</body>
</html>