jQuery Example | Check and Uncheck All Checkboxes in Page

This jquery example code will show us how to check and uncheck all checkboxes in a html page.

Step 1: Create a html page that contains some checkboxes

<!DOCTYPE html>
<html>
<body>
<table border="1" cellspacing="0" cellpadding="10">
<tbody class="checkbox-group">
<tr>
<td><input type="checkbox" /></td><td>First Checkbox </td>
</tr>
<tr>
<td><input type="checkbox" /></td><td>Second Checkbox</td>
</tr>
<tr>
<td><input type="checkbox" /></td><td>Third Checkbox</td>
</tr>
<tr>
<td><input type="checkbox" /></td><td>Fourth Checkbox</td>
</tr>
<tr>
<td><input type="checkbox" /></td><td>Fifth Checkbox </td>
</tr>
</tbody>
<tfoot>
<tr>
<td><input type="checkbox" id="singleCheckbox" /></td>
<td><b>Check all</b></td>
</tr>
</tfoot>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>

You should notice: we have used jquery.min.js and custom.js

Step 2: Create custom.js

<script type="text/javascript">

$(document).ready(function(){

    const singleCheckbox = '#singleCheckbox';
    const checkboxGroup = ".checkbox-group input[type='checkbox']";
    $(singleCheckbox).on('click',function(){
        if(this.checked){
            $(checkboxGroup).each(function(){
                this.checked = true;
            });
        }else{
             $(checkboxGroup).each(function(){
                this.checked = false;
            });
        }
    });
    
    $(checkboxGroup).on('click',function(){
        if($(checkboxGroup+':checked').length == $(checkboxGroup).length){
            $(singleCheckbox).prop('checked',true);
        }else{
            $(singleCheckbox).prop('checked',false);
        }
    });
});

</script>