Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking all checkboxes jquery

Why in my js code can just with one click on name:check_all checking all checkboxes?

HTML:

<div id="ss">
    <input type="checkbox" name="check_all">
</div>
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">
<input type="checkbox" name="checked" class="idRow">

jQuery:

$(document).on('click change','input[name="check_all"]',function() {
    var checkboxes = $('.idRow');
    if($(this).is(':checked')) {
        checkboxes.attr("checked" , true);
    } else {
        checkboxes.attr ( "checked" , false );
    }
});

DEMO: http://jsfiddle.net/KdaZr/

My jQuery version is 1.9.

How can fix it?

like image 226
Taylor Gomez Avatar asked Feb 17 '13 20:02

Taylor Gomez


2 Answers

Use .prop, not .attr, to change properties of elements. .attr is for HTML attributes.

http://jsfiddle.net/KdaZr/1/

like image 31
Explosion Pills Avatar answered Oct 22 '22 15:10

Explosion Pills


Use prop method. When your markup is rendered attributes become properties of the elements, using JavaScript you should modify properties of the element.

$(document).on('change','input[name="check_all"]',function() {
    $('.idRow').prop("checked" , this.checked);
});

http://jsfiddle.net/GW64e/

Note that if input[name="check_all"] is not generated dynamically there is no need to delegate the event.

like image 70
undefined Avatar answered Oct 22 '22 17:10

undefined