Question about the checked attribute of the input obtained by the jquery attr Method

Source: Internet
Author: User

Problem: the attr method of jQuery plug-in is often used to obtain the checked attribute value. The size of the obtained value is undefined. In this case, you can use the prop method to obtain the actual value. The differences between the two methods are described below:

1. Use the prop method to obtain the checked attribute. The returned value of checked is boolean, and the value is true. Otherwise, the value is flase.
Copy codeThe Code is as follows:
<Input type = "checkbox" id = "selectAll" onclick = "checkAll ()"> select all
Function checkAll ()
{
Var checkedOfAll = $ ("# selectAll"). prop ("checked ");
Alert (checkedOfAll );
$ ("Input [name = 'check']"). prop ("checked", checkedOfAll );
}

2. if the checked attribute is not defined during initialization in the current input when the attr method is used, $ ("# selectAll") is selected or not "). attr ("checked") will return undefined;
Copy codeThe Code is as follows:
<Input type = "checkbox" id = "selectAll" onclick = "checkAll ()"> select all

If the checked attribute is defined in the initialization of the current input, $ ("# selectAll"). attr ("checked") will return checked no matter whether or not it is selected.
Copy codeThe Code is as follows:
<Input type = "checkbox" id = "selectAll" onclick = "checkAll ()" checked> select all
Function checkAll ()
{
Var checkedOfAll = $ ("# selectAll"). attr ("checked ");
Alert (checkedOfAll );
$ ("Input [name = 'check']"). attr ("checked", checkedOfAll );
}

To sum up, if jquery is used, the prop method should be used to obtain and set the checked attribute. attr should not be used.

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.