Categories
JavaScript Answers

How to Check All Checkboxes Using jQuery?

Spread the love

Sometimes, we want to check all checkboxes with jQuery.

In this article, we’ll look at how to check all checkboxes with jQuery.

Set the checked Property

We can use jQuery to set the checked attribute of each checkbox element.

For instance, if we have the following HTML:

<div>  
  <input type="checkbox" id="checkAll">check all  
  <input type='checkbox' value='apple'> apple  
  <input type='checkbox' value='orange'> orange  
  <input type='checkbox' value='grape'> grape  
</div>

Then we can write the following JavaScript code to check all the checkboxes when we click check all:

$("#checkAll").click(function() {  
  $('input:checkbox').prop('checked', this.checked);  
});

We get the checkbox with ID checkAll and add a click listener to it with click .

Then in the click handler callback, we get all the checkboxes and set the checked attribute of each of them to the checked value of the checkbox with ID checkAll .

Therefore, when we click check all, they’ll all be checked on and off at the same time.

Conclusion

We can use jQuery to set the checked attribute of each checkbox element.

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 *