Jqueryattr ("checked") returns checked or undefined to get the selected INVALID _ jquery

Source: Internet
Author: User
$ (# Cb ). attr (checked); The returned values are checked or undefined, not true or false. The solution to this problem is as follows, if you are interested, you can refer to the following scenario where we need to: There is a checkbox on the page, and we hope to use Jquery to determine whether it is selected or whether it is selected through Jquery.
In versions earlier than JQ1.6, We will write our Code as follows:

The Code is as follows:



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:

The Code is as follows:



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.

The 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.