Home > Web Front-end > JS Tutorial > body text

Example code for selecting all and inverting selection in jQuery (recommended)

怪我咯
Release: 2017-03-30 09:27:27
Original
1497 people have browsed it

1. Overview

In projects, we often encounter the check box operation in the list, select all. . . Counter election. .

2. example

<html>
<body>
<form id="test-form" action="test">
<legend>请选择想要学习的编程语言:</legend>
<fieldset>
<p><label class="selectAll"><input type="checkbox"> <span class="selectAll">全选</span><span class="deselectAll">全不选</span></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>
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(function(){
(function(){
var
form = $(&#39;#test-form&#39;),
langs = form.find(&#39;[name=lang]&#39;),
selectAll = form.find(&#39;label.selectAll :checkbox&#39;),
selectAllLabel = form.find(&#39;label.selectAll span.selectAll&#39;),
deselectAllLabel = form.find(&#39;label.selectAll span.deselectAll&#39;),
invertSelect = form.find(&#39;a.invertSelect&#39;);
// 重置初始化状态:
form.find(&#39;*&#39;).show().off();
form.find(&#39;:checkbox&#39;).prop(&#39;checked&#39;, false).off();
deselectAllLabel.hide();
// 拦截form提交事件:
form.off().submit(function (e) {
e.preventDefault();
alert(form.serialize());
});
var count = 1; //点击全选/全不选框次数
selectAll.click(function(){
if(count++ %2){
selectAllLabel.hide();
deselectAllLabel.show();
$(this).prop("checked", false);
langs.prop("checked", true);
}else {
selectAllLabel.show();
deselectAllLabel.hide();
$(this).prop("checked", false);
langs.prop("checked", false);
}
});
invertSelect.on(&#39;click&#39;, function(){
langs.map(function(){
$(this).prop(&#39;checked&#39;, !this.checked);
});
});
})();
});
</script>
</body>
</html>
Copy after login


The above is the detailed content of Example code for selecting all and inverting selection in jQuery (recommended). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!