Recently, this film needs to be designed to provide a checkbox function that is selected all.
Oh, isn't this a very simple thing? One general checkbox, N multiple sub-checkboxes. Once the general checkbox is selected, all sub-checkboxes are selected. Once the general checkbox is not selected, the sub-checkboxes are not selected.
After getting this small request, I was secretly happy. What a simple function, OK, it will be done in two minutes~~~
Time passed by minute by minute, and the horses on the prairie rushing in my heart gradually increased from all the time to tens of millions~~~
What's going on with this?
alert($("#checkbox_all").attr("checked"));
Always undefined?
Nani? ? ?
Why is this happening? ? Are you stupid in the browser? Then decisively change browsers to test, from chrome to IE, from IE to Firefox. This is the result-_-||
Could it be that jquery has made improvements? ? ? ?
After checking with Hubble Telescope and HD laser electron microscope, we finally found the clue. . . .
It turns out that this has been modified in jquery version 1.6:
[The checked attribute has been initialized when the page is initialized and will not change with the change of state.
That is to say, if checkbox is selected after the page is loaded, then the returned one will always be checked (I didn't select it from the beginning)
If it is not selected at the beginning, the returned one will always be undefined! 】
Since jquery has made changes to this, there must be a corresponding better solution:
.prop() is the weapon to solve this problem!
The specific usage is as follows:
alert($("#checkbox_all").prop("checked"));
It will become true or false at this time~~
So, the code of this stream was changed to the following:
#check_all is the total checkbox selected all, and #check_children is the child checkbox
The code copy is as follows:
$("#check_all").change(function(){
$('.check_children').prop("checked", this.checked);
});
or:
The code copy is as follows:
$("#check_all").change(function(){
var is_checked = $(this).prop("checked");
$('.check_children').prop("checked",is_checked);
});
However, I still like using the first method very much. The less code, the better~~write less, do more!
It's very convenient to solve the problem of choosing all ~~~