Categories
JavaScript Answers

How to select all checkboxes with jQuery?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *