Jquery Select all checkbox example
Posted on: October 19, 2021 by Deven
A checkbox is an HTML input that lets a user select one or more options of a limited number of choices. Checkboxes are defined using <input type="checkbox">
. Sometimes we need to automatically check/uncheck all checkboxes when a single checkbox is checked / unchecked. For eg: A list of 5 items inside a combo, the user can select any item or select all the items.
<input type="checkbox" id="selectAll" class="css-checkbox" name="selectAll"/>
Selectall<br>
<input type="checkbox" class="checkboxAll" value="checkbox1"/>checkbox1<br>
<input type="checkbox" class="checkboxAll" value="checkbox2"/>checkbox2<br>
<input type="checkbox" class="checkboxAll" value="checkbox3"/>checkbox3<br>
Solution 1:
In the below solution we are looping each elements whose class is checkboxAll & marking it’s property checked as true. Each method will iterates over the DOM elements that are part of the jQuery object.
$(document).ready(function(){
$("#selectAll").click(function(){
if(this.checked){
$('.checkboxAll').each(function(){
$(".checkboxAll").prop('checked', true);
})
}else{
$('.checkboxAll').each(function(){
$(".checkboxAll").prop('checked', false);
})
}
});
});
Solution 2:
In the below solution we are marking property checked of class checkboxAll to true. This will make all the checkbox marked whose class is set as checkboxAll.
$("#selectAll").click(function () {
$(".checkboxAll").prop('checked', $(this).prop('checked'));
});
Share on social media
//