0

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().

Community
  • 1
  • 1
jtheman
  • 7,421
  • 3
  • 28
  • 39

1 Answers1

3

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
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Sure. But if you explain why my code doesn't work I'll mark this as the suggested answer. – jtheman May 28 '15 at 09:44
  • Why can't it be added again? Where is that documented? I'm looking for an explanation just by curiosity. Since the `.attr('checked','checked')` can add the attribute once, why can't it be added another time after being removed? It didn't exist there at the first time either. – jtheman May 28 '15 at 09:56