Question

I have a table that has checkbox column and I added this :

<th>
    <input type="checkbox" id="selectAll">
</th>

and here's my jQuery function :

jQuery(document).ready(function() {
   jQuery('#selectAll').click(function(){ 
   jQuery("input[type='checkbox']").attr('checked', jQuery('#selectAll').is(':checked')); }) 
});

It works fine at the first check but when i uncheck and try to check again it doesn't work! Any reason why it doesn't work? Thanks

Was it helpful?

Solution

Try to use .prop() and this.checked:

jQuery(document).ready(function() {
   jQuery('#selectAll').click(function(){ 
       jQuery("input[type='checkbox']").prop('checked', this.checked); 
    }) 
});

OTHER TIPS

When you choose by id on jquery it choose the first element by default, so your jQuery('#selectAll').is(':checked') will return the result of the first element, try using a class for selectAll instead :

<th>
    <input type="checkbox" class="selectAll">
</th>



jQuery(document).ready(function() {
   jQuery('.selectAll').click(function(){ 
   jQuery("input[type='checkbox']").attr('checked', jQuery('.selectAll').is(':checked')); }) 
});

this should work:

$('input#selectAll').change(function(){

    $('input[type="checkbox"]').prop("checked",this.checked);

});

Fiddle DEMO

Take a look at this

Working Demo

Html

<p><input type="checkbox" id="selectAll" /> Check/Uncheck All</p>
<hr/>
<p>
<input type="checkbox" class="chk" /> Checkbox  1
<input type="checkbox" class="chk" /> Checkbox  2
<input type="checkbox" class="chk" /> Checkbox  3
</p>

Script

$(document).ready(function () {
    $("#selectAll").click(function () {
        $("input[type='checkbox']").prop("checked", $("#selectAll").prop("checked"))
    })
});

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

jQuery(document).ready(function() {
   jQuery('#selectAll').click(function(){ 
   jQuery("input[type='checkbox']").prop('checked', jQuery('#selectAll').is(':checked')); }) 
});

Working Example

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top