Home >Web Front-end >JS Tutorial >Jquery solution for selecting all and inverting selections and executing it once with one click_jquery
Code requirements: using attr can only be executed once, using prop can perfectly realize all selection and inverse selection, obtain all selected items and form the text of the selected item into a string.
Solution 1:
The code is as follows:
<html> <head> <script src="jquery-1.11.1.min.js" type="text/javascript"></script> </head> <body> <input type="checkbox" name="chk_list[]" value="1" />1 <input type="checkbox" name="chk_list[]" value="2" />2 <input type="checkbox" name="chk_list[]" value="3" />3 <input type="checkbox" name="chk_list[]" value="4" />4 <input type="checkbox" name="chk_all" id="chk_all" />全选/取消全选 <script type="text/javascript"> $("#chk_all").click(function(){ // 使用attr只能执行一次 $("input[name='chk_list[]']").attr("checked", $(this).attr("checked")); // 使用prop则完美实现全选和反选 $("input[name='chk_list[]']").prop("checked", $(this).prop("checked")); // 获取所有选中的项并把选中项的文本组成一个字符串 var str = ''; $($("input[name='chk_list[]']:checked")).each(function(){ str += $(this).next().text() + ','; }); alert(str); }); </script> </body> </html>
Summary:
For the inherent attributes of the HTML element itself, use the prop method when processing.
For our own custom DOM attributes of HTML elements, use the attr method when processing them.
Reference http://www.jb51.net/article/62308.htm
Solution 2:
Problem description:
$(".chooseall").click(function(){ if($(".chooseall").attr("checked") == "checked"){ $("input[name='checkbox1']").removeAttr("checked","checked"); console.log(1); }else{ $("input[name='checkbox1']").attr("checked","checked"); console.log(2); } });
The first and second clicks of the above code can realize the selection and inverse selection functions, but it no longer works after one time. What is going on?
Except for the first checkbox, the rest are dynamically generated by ajax. Does this have anything to do with it? Console.log can alternately output 1 and 2 every time it is clicked, but the code in the middle cannot be executed.
Solution:
Only one removeAttr parameter is required, removeAttr("checked")
However, it is recommended to replace it with
$(".chooseall").click(function(){ if($(".chooseall").prop("checked") == true){ $("input[name='checkbox1']").prop("checked", false); console.log(1); }else{ $("input[name='checkbox1']").prop("checked", false); console.log(2); } });
Or more concisely,
$(".chooseall").click(function(){ var isChecked = $(this).prop("checked"); $("input[name='checkbox1']").prop("checked", isChecked); });
The above is the Jquery solution for selecting all and inverting the selection with one click. I hope it will be helpful to everyone.