Check and Uncheck all checkboxes with jQuery
![check and uncheck all checkboxes using jquery](https://sbsharma.com/wp-content/uploads/2021/06/check-and-uncheck-all-checkboxes-using-jquery-min.png)
How to create check and uncheck all checkboxes with check-all feature.
Hello guys, we are going to learn some jQuery today.
Terminology : we will call the “check all” checkbox a major checkbox and others will be single checkboxes.
Case: 1. Check all when you click on the major checkbox.
It’s so simple, just assign the checked status of the major checkbox to all single checkboxes.
E.g. if the major checkbox is checked true then all single checkboxes will be checked. If a major checkbox is false then all checkboxes will be unchecked.
Case: 2. Uncheck the major checkbox if you uncheck any single checkbox.
If you have checked the major checkbox then uncheck any of the single checkbox it will uncheck the major checkbox too.
Case: 3. Check the major checkbox if you check all other single checkboxes one by one.
For example, if you check mark all single checkboxes one by one then the major checkbox (check-all) must be checked automatically.
You can set the values to these checkboxes and get the value in your backend code. I have written on how to get the value of selected radio buttons with js.
Final code
<div class="container"> <div class="card text-center mt-5"> <div class="card-header"> Check and Uncheck all </div> <div class="card-body"> <table class="table table-striped table-bordered border-primary"> <thead> <tr> <th scope="col"> <input class="form-check-input check-all-js" type="checkbox" value="all"> </th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row"> <input class="form-check-input single-check-js" type="checkbox" value="1"> </th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row"> <input class="form-check-input single-check-js" type="checkbox" value="2"> </th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row"> <input class="form-check-input single-check-js" type="checkbox" value="3"> </th> <td>Larry the Bird</td> <td>Thornton</td> <td>@twitter</td> </tr> </tbody> </table> </div> <div class="card-footer text-muted"> 2 days ago </div> </div> </div>
$(function() { // check and uncheck all single checkboxes with check-all checkbox $('.check-all-js').on('change', function() { var single_check = $('.single-check-js'); single_check.each((index, element) => { element.checked = this.checked; }) }) // check and uncheck major (check-all) checkbox with single checkboxes $('.single-check-js').on('change', function() { var single_check = $('.single-check-js'); var all_checked = true; single_check.each((index, element) => { if ( element.checked === false ) { all_checked = false; } }) document.querySelector('.check-all-js').checked = all_checked; }) })
Hope you find this article useful, please share it with your friends.