To select all checkboxes using jQuery, you can use the prop()
method to set the checked
property of each checkbox to true
.
To do this we write
<!-- HTML checkboxes -->
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<!-- jQuery code to select all checkboxes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#selectAll').click(function(event) {
// Iterate through each checkbox
$('.checkbox').each(function() {
// Set checked property to true
$(this).prop('checked', true);
});
});
});
</script>
In this code, each checkbox has a class of “checkbox” to select them collectively.
There’s a button (or any element with the id “selectAll”) that, when clicked, will trigger the jQuery code.
Inside the jQuery code, the each()
function iterates through each checkbox with the class “checkbox”.
For each checkbox, the prop()
function sets the checked
property to true
, effectively selecting all checkboxes.
This code will select all checkboxes when the “Select All” button (or any element with the id “selectAll”) is clicked.