How do I check/uncheck all checkboxes with a button using jQuery?
This is the shortest way I've found (needs jQuery1.6+)
HTML:
<input type="checkbox" id="checkAll"/>
JS:
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.
Example-
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<fieldset>
<legend>Loads of checkboxes</legend>
<p><label><input type="checkbox" /> Option 1</label></p>
<p><label><input type="checkbox" /> Option 2</label></p>
<p><label><input type="checkbox" /> Option 3</label></p>
<p><label><input type="checkbox" /> Option 4</label></p>
</fieldset>
</form>
Try This One:
HTML
<input type="checkbox" name="all" id="checkall" />
JavaScript
$('#checkall:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
DEMO
Try this one :
$(document).ready(function(){
$('.check:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$(this).val('uncheck all');
},function(){
$('input:checkbox').removeAttr('checked');
$(this).val('check all');
})
})
DEMO