Flash Thunder
Flash Thunder

Reputation: 12045

jQuery check all checkboxes works only once

Why this function on Chrome is not working second time?

$('.main').on('change','input[name="select_all"]',function(){
   if($(this).is(':checked')){
      $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',true);
   }else{
      $('input[type="checkbox"]',$(this).parent().parent().parent()).removeAttr('checked');
});

On first click it checks all, on second it unchecks all... but on third does nothing...

jsfiddle

PS. It does add and remove checked attributes, but visually it does not change.

Chrome 31.0.1650.57 m

Upvotes: 3

Views: 1356

Answers (2)

joews
joews

Reputation: 30340

Use prop instead of attr:

$('.main').on('change','input[name="select_all"]',function(){
    if($(this).is(':checked')){
        $('input[type="checkbox"]',$(this).parent().parent().parent()).prop('checked',true);
    }else{
        $('input[type="checkbox"]',$(this).parent().parent().parent()).prop('checked', false);
    }
});

The jQuery documentation explains the difference and lists some of the cases where you should use prop.

Upvotes: 8

epikfaal
epikfaal

Reputation: 25

$('.main').on('change','input[name="select_all"]',function(){
   if($(this).is(':checked')){
      $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',true);
   }else{
  $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',false);
});

I hope this is what you are looking for

Upvotes: -1

Related Questions