$ (& #39; # checkbox & #39;). attr (& #39; checked & #39;); Return checked or undefined Solution

Source: Internet
Author: User

$ ('# Checkbox'). attr ('checked'); The returned value is checked or undefined, not true or false. The solution to this problem is as follows:


In versions earlier than JQ1.6, We will write our Code as follows:

<Input type = 'checkbox' id = 'cb '/> <script> // obtain whether to select var isChecked = $ (' # cb '). attr ('checked'); // you can specify $ ('# 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.

<Input type = 'checkbox' id = 'cb '/> <script> // obtain whether to select var isChecked = $ (' # cb '). prop ('checked'); // or var isChecked = $ ('# cb '). is (": checked"); // sets 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.

$("#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.