Jquery attr (& quot; checked & quot;) returns checked or undefined

Source: Internet
Author: User

Suppose we need a scenario like this: there is a checkbox on the page, and we expect to use Jquery to determine whether it is selected, or use Jquery to make it selected.
In versions earlier than JQ1.6, We will write our Code as follows:
Copy codeThe Code is as follows:
<Input type = 'checkbox' id = 'cb '/>
<Script>
// Obtain whether or not selected
Var isChecked = $ ('# cb'). attr ('checked ');

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

This is done before JQ1.6, but when we upgrade JQ1.6 to a later version, the problem arises. At this time, we will find:
$ ('# Cb'). attr ('checked'); The returned value is checked or undefined, not true or false.
In addition, the checked attribute has been initialized during page initialization and will not change as the status changes. Therefore, if the checkbox is selected at the beginning, the returned value is checked. If it is not selected at the beginning, the returned value is undefined.

The solution is:
Copy codeThe Code is as follows:
<Input type = 'checkbox' id = 'cb '/>
<Script>
// Obtain whether or not selected
Var isChecked = $ ('# cb'). prop ('checked ');
// Or
Var isChecked = $ ('# cb'). is (": checked ");
// Set the selected
$ ('# Cb'). prop ('checked', true );
</Script>

The reason is analyzed. You can understand it as follows:

It distinguishes "attributes" from "Features". attributes refer to "name, id", and so on, and features refer to "selectedIndex, tagName, nodeName.
After JQ1.6, attributes can be obtained through the attr method and features can be obtained through the prop method.
Copy codeThe Code is as follows:
$ ("# Cb"). attr ("tagName"); // undefined
$ ("# Cb"). prop ("tagName"); // INPUT

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.