How to check all checkboxes using jQuery?

Ivan picture Ivan · Aug 30, 2013 · Viewed 340.5k times · Source

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/

Answer

Arun P Johny picture Arun P Johny · Aug 30, 2013

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

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

Demo: Fiddle