Home > Article > Web Front-end > Solve the problem that the attr (checked) of checkbox is always undefined_jquery
Recently, in response to project development needs, I need to create an all-select checkbox function.
Oops~~ Isn’t this a very simple thing? There is a general checkbox and N sub-checkboxes. Once the general checkbox is selected, all the sub-checkboxes are selected. Once the general checkbox is not selected, the sub-checkboxes are not selected. Selected.
After receiving this small request, I was secretly happy. What a simple function. OK, it will be done in two minutes~~~
Time passed by minute by second, and my heart was racing. The number of horses in the grasslands has gradually increased to tens of millions~~~
What the hell is going on?
alert($("#checkbox_all").attr("checked"));
Always undefined?
Nani? ? ?
Why is this happening? ? Browser, are you stupid? Then decisively change browsers for testing, from chrome to IE, and from IE to Firefox. The result is like this -_-||
Is it because jquery has been improved again? ? ? ?
After Ben Diaosi used the Hubble Telescope and a high-definition laser electron microscope to check, we finally found the clue. . . .
It turns out that this was modified in jquery version 1.6:
[The checked attribute has been initialized when the page is initialized and will not change with the status. And change.
That is to say, if the checkbox is selected after the page is loaded, the returned value will always be checked (mine was not selected at the beginning)
If it is not selected at the beginning, it will be returned is always undefined! 】
Since jquery has made changes to this, there must be a corresponding and better solution:
.prop() is a powerful tool to solve this problem!
The specific usage is as follows:
alert($("#checkbox_all").prop("checked"));
will become true at this time Or false~~
So, the code of this diaosi was changed to the following:
#check_all is the total checkbox for all selections, #check_children is the sub-checkbox