Resolve that the attr of checked in the checkbox is always undefined

  • 2020-03-30 03:23:22
  • OfStack

Recently, in response to project development requirements, we needed to make a fully selected checkbox feature.

If the checkbox is checked, all the checkboxes are checked. If the checkbox is not checked, all the checkboxes are checked.

Get this small demand, Ben zhusi a burst of joy, what a simple function ah, OK, two minutes to finish ~ ~ ~

As time went by, the number of horses galloping on the grassland inside Ben zhusi gradually increased to tens of thousands

What the hell is going on?
Alert ($(" # checkbox_all "). The attr (" checked "));
Undefined?


Nani??

Why did this happen? Are browsers stupid? Then switch browser tests decisively, from chrome to IE, from IE to firefox. So this is all -_-|, |

Is jquery improving again??

With the help of the Hubble space telescope and a high-definition laser electron microscope, Ben jacobs finally found the clue...

Originally, this was changed in version 1.6 of query1:

The checked property is initialized when the page is initialized and does not change as the state changes.

That is, if the checkbox is checked after the page has loaded, it will always return checked.

If not initially selected, it always returns undefined! 】


Since jquery has changed this, there must be a better solution:

.prop() is the solution to this problem!

The specific usage is as follows:

Alert ($(" # checkbox_all "). The prop (" checked "));
This will change to true or false ~~


As a result, the code of Ben zhusi was changed to the following:

#check_all is the total checkbox selected for all, and #check_children is the child checkbox
 
$("#check_all").change(function(){ 
$('.check_children').prop("checked",this.checked); 
}); 

Or:
 
$("#check_all").change(function(){ 
var is_checked = $(this).prop("checked"); 
$('.check_children').prop("checked",is_checked); 
}); 

However, I still like to use the first method, the less code the better ~~write less,do more!

Very convenient to solve the problem of all selection ah ~~~

Related articles: