<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全选练习</title>
<script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<form action="http://www.baidu.com" method="post">
<p>你喜欢的食物?</p>
<input type="checkbox" name="foods" value="麦当劳" />麦当劳
<input type="checkbox" name="foods" value="肯德基" />肯德基
<input type="checkbox" name="foods" value="汉堡王" />汉堡王
<input type="checkbox" name="foods" value="必胜客" />必胜客
<p>
<input type="checkbox" id="checkAll" />全选/全不选
<input type="button" id="reverse" value="反选" />
<input type="button" id="submit" value="提交" />
</p>
</form>
</body>
</html>
<script>
$(function () {
const checkAll = $('#checkAll'); // 全选/不全选
const checkboxALL = $(':checkbox[name = foods]'); // 所有元素checkbox
const reverse = $('#reverse'); // 反选
const submit = $('#submit'); // 提交
// 全选与取消全选
checkAll.click(function () {
checkboxALL.prop('checked', this.checked);
});
// 反选
reverse.click(function () {
$.each(checkboxALL, function() {
this.checked = !this.checked;
});
checkAll.prop('checked', checkboxALL.filter(':not(:checked)').length === 0); // 是否全选
});
// 单个点击
checkboxALL.click(function () {
console.log(this.value); // 获取点击checkbox的属性
checkAll.prop('checked', checkboxALL.filter(':not(:checked)').length === 0); // 是否全选
});
// 提交
submit.click(function () {
let checkboxValue = []; // 所有选中的checkbox的值
checkboxALL.filter(':checked').each(function () {
checkboxValue.push(this.value);
});
})
})
</script>
判断某个checkbox是否选中,返回值: Boolean
$("#XXX").eq(index).is(':checked')
$("#XXX")[index].checked
设置某个checkbox的选中与不选中
$("#XXX").eq(index).prop('checked', true/false)