ShaneKm
ShaneKm

Reputation: 21328

jquery check/uncheck list of checkboxes

Since upgrading to jquery 1.9 my script stopped working for checking/unchecking checkboxes.

I have a main check box that controls selecting/checking a list of checkboxes in a table. After upgrading to new jquery version only initially clicking "Check all" checkboxes get selected. Clicking the second time "Check all" causes checkboxes to uncheck, BUT doing "Check all" click after 2 clicks table checkboxes cease to work anymore.

enter image description here

script:

    $("#itemsList .checkall").on("click", function () {
        $(".checkbox").attr("checked", $(this).is(':checked'));
    });

also tried this:

    $("#itemsList .checkall").click(function () {
        $(".checkbox").attr("checked", $(this).is(':checked'));
    });

html "Check all":

<input type="checkbox" id="checkall" name="checkall" class="checkbox checkall">

html table checkboxes:

<input type="checkbox" value="1" class="checkbox">

this used to work just fine before switching to jquery 1.9. what gives??

Upvotes: 1

Views: 3753

Answers (2)

Eli
Eli

Reputation: 14827

Try to use prop() instead since:

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

$("#itemsList .checkall").on("change", function () {
    $(".checkbox").prop("checked", this.checked);
});

Upvotes: 2

Ram
Ram

Reputation: 144689

As of jQuery 1.6 for changing properties of elements prop method should be used instead of attr.

$("#itemsList .checkall").on("change", function () {
     $(".checkbox").prop("checked", this.checked);
});

Upvotes: 2

Related Questions