jtheman
jtheman

Reputation: 7491

Toggle checkboxes with jQuery works only twice

I have this old code for selecting all checkboxes with the class .sselect, and subsequently unselecting all checkboxes again with the same button #selectall

The code works twice, selecting all checkboxes and then unselecting them again, but not any more. Any suggestions why?

$(function() {  
    var tog = true;
    $('a#selectall').click(function() {
        if (tog) {
            $('input.sselect').attr("checked","checked");
            $(this).html('<i class="fa fa-check-circle"></i> Unselect all');
        }
        else {
            $('input.sselect').removeAttr('checked'); 
            $(this).html('<i class="fa fa-check"></i> Select all');
        }
        tog = !tog;
    });
}); 

UPDATE Using prop() solves the issue, but doesn't explain why attr() works once but not twice. I read in the jQuery documentation:

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.

But why would the code above actually fail to set the attributes? It works the first time, why doesn't it work the next?

This answer shreds some light on the topic: Setting "checked" for a checkbox with jQuery? - but the issue as I see it is not that the form is reset but that the attribute cannot be readded after being removed with removeAttr().

Upvotes: 0

Views: 554

Answers (1)

Tushar
Tushar

Reputation: 87203

Once the checked attribute is removed, it cannot not be added again.

You should use prop instead of attr:

$('input.sselect').prop("checked", true); // Check


$('input.sselect').prop("checked", false); // Unheck

Upvotes: 3

Related Questions