简体   繁体   中英

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

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 .

$('.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM