Jquery cannot set the checkbox to be checked or it does not become checked

  • 2020-03-30 02:29:59
  • OfStack

 
$("input").attr("checked","checked") 

After setting the checkbox, it does not become checked state. After debugging with chrome, it does have checked property in the checkbox, and the value is checked, but the page is still unchecked
 
$("input").prop("checked",true); 


The difference between ttributes and properties is important in certain cases. Before jQuery 1.6, the.attr() method returned the value of the property when it took the value of some attributes, which resulted in inconsistent results. Starting with jQuery 1.6, the.prop() method method returns the value of the property, while the.attr() method returns the value of the attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be evaluated or assigned using the.prop() method. Prior to jQuery1.6, these attributes were obtained using the.attr() method, but this is not an attr attribute of the element. They have no attributes, just properties.

For example, consider the < Input type = "checkbox checked =" checked "/" > , and assume that it is a JavaScript variable named elem:

Elem.checked true (Boolean) changes the state of the check box
$(elem).prop("checked") true (Boolean) changes the state of the check box
Elem.getattribute ("checked") "checked" (String) does not change the initial state of the check box;
$(elem).attr("checked") (1.6) "checked" (String) does not change the initial state of the check box;
$(elem).attr("checked") (1.6.1+) "checked" (String) will change the state of the check box
$(elem).attr("checked") (pre-1.6) true (Boolean) changes the state of the check box
According to the W3C form specification, the checked property is a Boolean property, which means that the property is true as long as the attribute exists, even if it has no value or an empty string. The following method is recommended for determining whether the checked attribute of a checkbox element is "true" in a browser-compatible way:
 
if ( elem.checked ) 
if ( $(elem).prop("checked") ) 
if ( $(elem).is(":checked") ) 

If you use jQuery 1.6, the code if ($(elem).attr("checked") will get an attribute that does not change the checkbox to be checked and checked. It is simply used to store the initial value of the default or selected property. To maintain backward compatibility, the.attr () method starts with jQuery 1.6.1 + and updates the property property in addition to returning the property value, so the Boolean attribute does not need to change its value via.prop (). It is recommended to use one of the above methods to get the value of checked.

Related articles: