index.html
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<!-- HTML结构 -->
<form id="test-form" action="test">
<legend>请选择想要学习的编程语言:</legend>
<fieldset>
<p><label class="selectAll"><input type="checkbox"></label> <a href="#0" class="invertSelect">反选</a></p>
<p><label><input type="checkbox" name="lang" value="javascript"> JavaScript</label></p>
<p><label><input type="checkbox" name="lang" value="python"> Python</label></p>
<p><label><input type="checkbox" name="lang" value="ruby"> Ruby</label></p>
<p><label><input type="checkbox" name="lang" value="haskell"> Haskell</label></p>
<p><label><input type="checkbox" name="lang" value="scheme"> Scheme</label></p>
<p><button type="submit">Submit</button></p>
</fieldset>
</form>
</body>
</html>
index.js
'use strict';
$(document).ready(function () {
var form = $('#test-form'),
langs = form.find('[name=lang]'),
selectAll = form.find('label.selectAll :checkbox'),
invertSelect = form.find('a.invertSelect');
// 全选或全不选
selectAll.click(function (e) {
if (selectAll.is(":checked")) {
langs.prop("checked", true);
} else {
langs.prop("checked", false);
}
});
// 反选
invertSelect.click(function (e) {
langs.each(function (index) {
$(this).prop("checked", !$(this).is(":checked"));
});
selectAll.prop("checked", isAllChecked());
});
// 各个选择框
langs.click(function (e) {
selectAll.prop("checked", isAllChecked());
});
// 判断是否全部选中
function isAllChecked() {
return langs.filter(":checked").length == langs.length;
}
});
补充说明:
-
判断多选框是否选中的方法:
var radio = $('#test-radio');
radio.attr('checked'); // 'checked'
radio.prop('checked'); // true
radio.is(':checked'); // true
类似的属性还有selected -
each接受的函数的第一个参数是index,函数中this是dom对象,不是jquery对象
-
利用过滤器判断是否全选
网友评论