需求:多选框实现全选、反选。 逻辑:只要有一个子复选框未勾选,全选框自动取消勾选;所有子复选框全部勾选时,全选框自动勾选。使用each遍历复选框。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm19.aspx.cs" Inherits="WebApplication1.WebForm19" %>
<!DOCTYPE html>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<style>
</style>
<script type="text/javascript">
$(function () {
//给全选框注册点击事件,控制所有sport复选框
$('#checkall').click(function () {
if ($(this).attr("checked")=='checked') {
$('input[name=sport]').attr('checked', $(this).attr("checked"));
}
else {
$('input[name=sport]').removeAttr('checked');
}
});
//给所有子复选框注册点击事件
$('input[name=sport]').click(CheckCheckBox);
//判断子复选框勾选状态,同步全选框
function CheckCheckBox() {
var isCheckAll = true;
$('input[name=sport]').each(function () {
if ($(this).attr("checked") != 'checked')
{
isCheckAll = false;
return false;//return false终止each循环
}
});
$('#checkall').attr('checked', isCheckAll);
}
//反选按钮
$('#btn').click(function () {
$('input[name=sport]').each(function () {
$(this).attr("checked", !$(this).attr("checked"));//勾选状态取反
});
CheckCheckBox();//同步更新全选框状态
})
});
</script>
</head>
<body>
<h2>你喜欢的运动</h2>
<input type="checkbox" id="checkall" />全选
<input type="button" id="btn" value="反选" /><br />
<input type="checkbox" name="sport" value="football" />足球<br />
<input type="checkbox" name="sport" value="ymq" />羽毛球<br />
<input type="checkbox" name="sport" value="basketball" />篮球<br />
<input type="checkbox" name="sport" value="ppq" />乒乓球<br />
<input type="checkbox" name="sport" value="wq" />网球<br />
</body>
</html>
Code language: HTML, XML (xml)
说明:
- 全选框点击:批量设置所有子复选框勾选状态
- 子复选框点击:通过
each循环遍历,判断是否全部选中,自动同步全选框 - 反选:遍历每个复选框,把勾选状态取反,执行完成后调用
CheckCheckBox更新全选框
Previous: 表单选择器
Next: 遍历元素 each函数