JQuery uses prop to set all and inverse examples of checkbox

Source: Internet
Author: User

We all know that JQuery can set the DOM properties by the Attr method, and naturally think of the $ (DOM). attr (' checked ', ' checked '); This method selects the checkbox, but there is a problem with the recent use of checkbox selection and reverse selection in the project:
After using the Attr method to set the selection, click the first time to set the reverse, but not the second time.

$ (function () {
var checkbox = $ ("input[type= ' checkbox ']");
Select All
$ (' #select-all '). Click (function () {
Checkbox.attr (' checked ', true);
});

Anti-election
$ (' #select-reverse '). Click (function () {
Checkbox.each (function (i, DOM) {
if ($ (DOM). attr (' checked ')) {
$ (DOM). Removeattr (' checked ');
} else {
$ (DOM). attr (' checked ', ' checked ');
}
});
});
});

After looking at some material, only to discover: for jquery 1.6.0+ version, want to use prop method to set.

$ (function () {
    var checkbox = $ ("input[type= ' checkbox ']");
   //Select All
& nbsp;   $ (' #select-all '). Click (function () {
        Checkbox.prop ("Checked", true);
   });
   //anti-select
    $ (' #select-reverse '). Click (function () {
         checkbox.prop ("Checked", function (index, attr) {
             return!attr;
       });
   });
});

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.