user2813936
user2813936

Reputation: 21

How to select all the checkboxes in Jquery?

<form>
    <input type="checkbox" name="newsletter" value="Hourly" checked="checked">  <input   type="checkbox" name="newsletter" value="Daily">
    <input type="checkbox" name="newsletter" value="Weekly" checked>
    <input type="checkbox" name="newsletter" value="Monthly">
    <input type="checkbox" name="newsletter" value="Yearly">
    <br><button id="selectall">Select All</button>
</form>
<script>
    var selectall = function() {
        $("input[type=checkbox]").attr("checked", "true");
    };
    $("#selectall").on("click", selectall);
</script>

I have written a JQuery script which will select all the checkboxes when I click on the button "Select All". Now, after selection, I will manually uncheck all the checkboxes and then press "Select All". But this time it fails in selecting all the checkboxes. How to prevent this?

Upvotes: 2

Views: 56

Answers (5)

Sudharsan S
Sudharsan S

Reputation: 15403

Please make sure your code should be in dom ready function inside. and use .prop() to check all the checkboxes

$(function() {

       var selectall = function() {
       $("input[type=checkbox]").prop("checked",true);    
       };
       $("#selectall").on("click", selectall );
});

Upvotes: 0

Kiran
Kiran

Reputation: 20293

You should use .prop() instead of .attr(). Try this:

var selectall = function() {
     $("input[type=checkbox]").prop("checked","true");    
};
$("#selectall").on("click", selectall );

DEMO

prop() vs attr() ref: .prop() vs .attr()

Upvotes: 0

Ankush Jain
Ankush Jain

Reputation: 7079

try this one

$("#selectall").on("click", function(){
    $("input[type=checkbox]").prop("checked","true");    
});

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

USe prop() instead of attr()

var selectall = function() {
     $("input[type=checkbox]").prop("checked","true");    
};
$("#selectall").on("click", selectall );

Fiddle

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

So that's why we have to use .prop() instead of .attr()

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

DEMO

Upvotes: 3

Related Questions