Reputation: 21
<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
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
Reputation: 20293
You should use .prop() instead of .attr(). Try this:
var selectall = function() {
$("input[type=checkbox]").prop("checked","true");
};
$("#selectall").on("click", selectall );
prop() vs attr() ref: .prop() vs .attr()
Upvotes: 0
Reputation: 7079
try this one
$("#selectall").on("click", function(){
$("input[type=checkbox]").prop("checked","true");
});
Upvotes: 0
Reputation: 25537
USe prop()
instead of attr()
var selectall = function() {
$("input[type=checkbox]").prop("checked","true");
};
$("#selectall").on("click", selectall );
Upvotes: 0
Reputation: 67217
So that's why we have to use .prop()
instead of .attr()
$("input[type=checkbox]").prop("checked","true");
Upvotes: 3