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 = $('#test-form'), langs = form.find('[name=lang]'), selectAll = form.find('label.selectAll :checkbox'), selectAllLabel = form.find('label.selectAll span.selectAll'), deselectAllLabel = form.find('label.selectAll span.deselectAll'), invertSelect = form.find('a.invertSelect'); // 重置初始化状态: form.find('*').show().off(); form.find(':checkbox').prop('checked', 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('click', function(){ langs.map(function(){ $(this).prop('checked', !this.checked); }); }); })(); }); </script> </body> </html>
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!