Using jQuery to Check All Boxes

If you want to include a "check all" option in any of your projects, it's actually pretty easy to do using jQuery. The snippet below demonstrates how to include a check all button that will check all of the inputs that fall within one fieldset tag. To start, make sure your HTML looks something like this:

<fieldset>
   <input type="checkbox" class="checkall"> Check all <br>
   <input type="checkbox"> Checkbox <br>
   <input type="checkbox"> Checkbox <br>
   <input type="checkbox"> Checkbox <br>
   <input type="checkbox"> Checkbox <br>
</fieldset>

So the first input type with the .checkall class is going to be the input that, when checked, will also check all the other boxes that are in that fieldset. The jQuery for achieving this effect is as follows:

$(function() {
    $('.checkall').click(function() {
        $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
    });
});

Again, this code will only apply the check all functionality to boxes within the fieldset of the check all button. If there are other checkboxes within a different fieldset, they won't be affected by the checking of this particular check all button (but if the code of another fieldset is exactly the same, checking that check all button will check all of the checkbox input fields in that particular fieldset). The code can be changed and customized to reflect your own classes.

 

 



Responsive Menu
Add more content here...