Jquery attr('checked') Returns checked or undefined to get checked out

  • 2020-03-26 21:20:56
  • OfStack

Suppose we now need a scenario where we have a checkbox on the page, and we expect to either get it checked through Jquery or get it checked through Jquery.
Prior to JQ1.6, we would write our code like this:
 
<input type='checkbox' id='cb'/> 
<script> 
//Get whether or not selected
var isChecked = $('#cb').attr('checked'); 

//Set the selected
$('#cb').attr('checked',true); 
</script> 

This was fine before JQ1.6, but when we upgrade to a higher version of JQ1.6, the problem arises.
$(' # cb). Attr (" checked "); It returns checked or undefined, not true or false.
And the checked property is already initialized when the page is initialized and will not change as the state changes. So if the checkbox is checked at first, it returns checked, and if it isn't checked at first, it returns undefined.

The solution is:
 
<input type='checkbox' id='cb'/> 
<script> 
//Get whether or not selected
var isChecked = $('#cb').prop('checked'); 
// or  
var isChecked = $('#cb').is(":checked"); 
//Set the selected
$('#cb').prop('checked',true); 
</script> 

After analyzing the reasons, it can be understood as follows:

It distinguishes "property" from "property", which means "name, id" and so on, which means "selectedIndex, tagName, nodeName" and so on.
After JQ1.6, properties can be obtained by attr method and properties by prop method
 
$("#cb").attr("tagName"); //undefined 
$("#cb").prop("tagName"); //INPUT 

Related articles: