How to check all checkboxes using jQuery? Ask Question

How to check all checkboxes using jQuery? Ask Question

I am not expert with jQuery but I have tried to create a little script for my application. I want to check all checkboxes but it isn't working correctly.

First I tried to use attr and after that I tried with prop but I'm doing something wrong.

I tried this first:

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').attr('checked','checked');
  } else {
      $('input:checkbox').removeAttr('checked');
  }       
});

But this didn't work.

Next: This worked better than above code

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').prop('checked',true);
  } else {
      $('input:checkbox').prop('checked', false);
  }       
});

Both examples don't work.

JSFiddle: http://jsfiddle.net/hhZfu/4/

ベストアンサー1

You need to use .prop() to set the checked property

$("#checkAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

Demo: Fiddle

おすすめ記事