Zend Zend - 6 months ago 20
Javascript Question

Jquery Checkbox check all

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. I tried googling for an answer but was unsuccessful.

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

Thanks

Answer

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

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

Demo: Fiddle