jeudi 28 mai 2015

Toggle checkboxes with jQuery works only twice [duplicate]

This question already has an answer here:

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 OK, 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?




Aucun commentaire:

Enregistrer un commentaire