Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery set all checkbox checked

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.

like image 443
user1995781 Avatar asked Jul 16 '14 06:07

user1995781


People also ask

How do you check all checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

How do I check all checkboxes?

In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.

How can I check all checkboxes within a div using jQuery?

click(function(){ $(':checkbox'). prop("checked", true); alert("1"); }); $('#deselectChb'). click(function(){ $(':checkbox'). prop("checked", false); alert("2"); });


2 Answers

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()

like image 65
Satpal Avatar answered Sep 29 '22 18:09

Satpal


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.

like image 26
Rajaprabhu Aravindasamy Avatar answered Sep 29 '22 20:09

Rajaprabhu Aravindasamy