How to check all checkboxes using jQuery?
Simply use the checked
property of the checkAll
and use use prop() instead of attr for checked property
$('#checkAll').click(function () { $('input:checkbox').prop('checked', this.checked); });
Use prop() instead of attr() for properties like checked
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
You have same id for checkboxes and its should be unique. You better use some class with the dependent checkboxes so that it does not include the checkboxes you do not want. As $('input:checkbox')
will select all checkboxes on the page. If your page is extended with new checkboxes then they will also get selected/un-selected. Which might not be the intended behaviour.
$('#checkAll').click(function () { $(':checkbox.checkItem').prop('checked', this.checked); });
A complete solution is here.
$(document).ready(function() { $("#checkedAll").change(function() { if (this.checked) { $(".checkSingle").each(function() { this.checked=true; }); } else { $(".checkSingle").each(function() { this.checked=false; }); } }); $(".checkSingle").click(function () { if ($(this).is(":checked")) { var isAllChecked = 0; $(".checkSingle").each(function() { if (!this.checked) isAllChecked = 1; }); if (isAllChecked == 0) { $("#checkedAll").prop("checked", true); } } else { $("#checkedAll").prop("checked", false); } });});
Html should be :
Single check box on checked three checkbox will be select and deselect.
<input type="checkbox" name="checkedAll" id="checkedAll" /><input type="checkbox" name="checkAll" class="checkSingle" /><input type="checkbox" name="checkAll" class="checkSingle" /><input type="checkbox" name="checkAll" class="checkSingle" />
Hope this helps to someone as it did for me.
JS Fiddle https://jsfiddle.net/52uny55w/