16

I am using jquery 1.11.1 and this is my code:

$("#rowchkall").change(function(){
    if($(this).is(':checked')){
        $("input:checkbox[class=rowchk]").each(function() {
            alert("set checked");
            $(this).attr('checked', "checked");
        });
    }else{
        $("input:checkbox[class=rowchk]").each(function() {
            $(this).attr('checked', false);
        });
    } 
});

When I first click on #rowchkall, all the checkbox is set to checked. When I click it again, all checkbox is unchecked.

When I click it again, alert box still appear but none of the checkbox will be checked. Why is it only work for first time only? How can I fix it?

Thank you.

user1995781
  • 19,085
  • 45
  • 135
  • 236

3 Answers3

31

Use .prop() instead of .attr()

$(this).prop('checked', true); //true to check else false uncheck

Your code can be simplified as

$("#rowchkall").change(function () {
    $("input:checkbox.rowchk").prop('checked',this.checked);
});

A Good Read .prop() vs .attr()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
6

Try to use .prop() instead of .attr()

$("#rowchkall").change(function(){
  $("input:checkbox[class=rowchk]").prop('checked', this.checked);
});

And you don't need to iterate over all the elements to change its property.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
3
$("#rowchkall").change(function(){
    if($(this).is(':checked')){
        $("input.rowchk[type=checkbox]").each(function() {
            alert("set checked");
            $(this).attr('checked',true);
        });
    }else{
        $("input.rowchk[type=checkbox]").each(function() {
            $(this).attr('checked', false);
        });
    } 
});
budamivardi
  • 722
  • 5
  • 10