Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Checking all check boxes when main check box is clicked

Yesterday i was giving an answer to one of the stackoverflow question that How to check/uncheck all checkboxes based on the selection of one checkbox and i came up with this solution. But the problem is it only works once but it will not work if you click it twice. FIDDLE

$('#allcb').click(function(){
    if ($('#allcb').is(':checked'))
    {
      $('.chk').each(function(){
        $(this).attr('checked', true);
      });
    }
    else
    {
        $('.chk').each(function(){
           $(this).attr('checked', false);
        });
    }
});

I found this code which works fine according to the requirements FIDDLE

So what is wrong with my approach? Either it should not work at all. If it works once why its not works twice?

Upvotes: 1

Views: 207

Answers (1)

adeneo
adeneo

Reputation: 318302

The reason it only works once is because you should have used prop(), not attr().

prop() changes the property, as in element.checked, while attr() changes the attribute, as in <input type="radio" checked="checked" />, and changing the attribute does not change the property, which is essentially what you want, as changing the attribute will only work once because the next time the property is checked it comes back the opposite of the attribute.

See this SO question for an overview of the difference between prop and attr.

$('#allcb').click(function(){
    if ($('#allcb').is(':checked'))
    {
      $('.chk').each(function(){
        $(this).prop('checked', true);
      });
    }
    else
    {
        $('.chk').each(function(){
           $(this).prop('checked', false);
        });
    }
});

FIDDLE

As a sidenote, that code can be summed up as :

$('#allcb').on('click', function(){
    $('.chk').prop('checked', this.checked);
});

FIDDLE

Upvotes: 6

Related Questions