Home > Article > Web Front-end > JQuery Select All Inverse Selection Second Failure Solution
This article mainly brings you an article to solve the problem of JQuery full selection/inverse selection failing for the second time. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Recently, I encountered a problem in the project. When testing the select/unselect function, when the parent box is selected/unselected for the first time, the all-selected/unselected state of the sub-box can be synchronized. , and then click the parent box, the child box will not respond.
The key to the general structure of the original code is as follows:
function selectAll(obj){ $('input[name="xxx[]"]').attr("checked",obj.checked); } <input type="checkbox" id="mother" name="mother" onclick="selectAll(this);"/>全选 <input type="checkbox" id="son1" name="xxx[]" />子框<input type="checkbox" id="son2" name="xxx[]" />子框<input type="checkbox" id="son3" name="xxx[]" />子框<input type="checkbox" id="son4" name="xxx[]" />子框
Step 1: Try a positive wave:
function selectAll(obj){ if(obj.checked) { $('input[name="xxx[]"]').attr("checked", true); } else { $('input[name="xxx[]"]').removeAttr("checked"); } }
Death ----- has no effect at all, discard it.
Step 2: After a quick search on the Internet, I found that this problem is relatively common. Among people who have encountered this problem, I should be thousands of miles away. I clicked on a few and looked at them. They basically said that using prop instead of attr can solve the problem. The solution is as follows:
However, the version used in the project is lower than 1.6 and I was told that the latest It is best not to change the version and discard it.
Step 3: There is no choice but to abandon JQuery... Try to use native js writing method. The code is as follows:
function selectAll(obj){ var xxx = document.getElementsByName("xxx[]"); if(obj.checked) { for(var i = 0;i < xxx.length;i++) { xxx[i].checked = true; } } else { for(var i = 0;i < xxx.length;i++) { xxx[i].checked = false; } } }
Test it and solve it smoothly. In fact, it is a small problem, but it gave me some inspiration. I cannot be limited to one box. If I think about the problem from another angle, I can often solve the problem better.
Related recommendations:
Share jquery select all and reverse selection examples
jquery select all checkBox function implementation code (cancel the select all function)_jquery
The above is the detailed content of JQuery Select All Inverse Selection Second Failure Solution. For more information, please follow other related articles on the PHP Chinese website!