Ashwin
Ashwin

Reputation: 12411

Check all checkbox does not work

In the jsfiddle

CODE:

<script type="text/javascript">
    function checkAll() {
    var checked = $("#checkAll").is(':checked');
    $(".check_row").attr("checked", checked);
}
</script>
<div>
    <input type="checkbox" id="checkAll" onclick="checkAll()" />Check All <br />
    <input type="checkbox" class="check_row" />One <br />
    <input type="checkbox" class="check_row" />Two <br />
    <input type="checkbox" class="check_row" />Three <br />
    <input type="checkbox" class="check_row" />Four <br />
    <input type="checkbox" class="check_row" />Five <br />
    <input type="checkbox" class="check_row" />Six <br />    
</div>

"check all" checkbox works for only first time. Can someone help me to find out what is wrong happening?

Upvotes: 0

Views: 711

Answers (5)

Thirumalai murugan
Thirumalai murugan

Reputation: 5896

  1. Since you are using jquery version greater then 1.6 not attribute are change from attr to prop in this
  2. Don't declare the variable many time if you declare the variable in function it will be repeatedly declaring the variable many time
  3. You don't even need the variable and if else conditions too... check my updated example

FIDDLE DEMO

var checked

function checkAll() {

    checked = $("#checkAll").is(':checked');

    $(".check_row").prop("checked", checked);

}

Update

FIDDLE DEMO

$('#checkAll').on('change',function(){    
    $(".check_row").prop("checked", $(this).is(':checked'));    
});

Upvotes: 2

Hardik Sondagar
Hardik Sondagar

Reputation: 4495

function checkAll() 
{
     var checked = $("#checkAll").is(':checked');

     $(".check_row").prop("checked", true);

    if(!checked)
    {
           $(".check_row").removeAttr("checked");
    }

}

JSFiddle

Upvotes: 0

Anoop
Anoop

Reputation: 993

change this line

    $(".check_row").attr("checked", checked); 

     to

    $(".check_row").attr("checked", true);

Fiddle : http://jsfiddle.net/auXdC/5/

Upvotes: 0

Vucko
Vucko

Reputation: 20834

$('#checkAll').on('change',function(){
    if($(this).is(':checked')){
        $(".check_row").prop("checked", true);
    }
    else{
        $(".check_row").prop("checked", false);
    }
});

JSFiddle

Upvotes: 1

gregjer
gregjer

Reputation: 2843

Change

$(".check_row").attr("checked", checked);

to

$(".check_row").prop("checked", checked);

See Fiddle

Upvotes: 3

Related Questions