Select All Checkboxes With JQuery

So, our web application has multiple checkboxes and we want to select them all at once to modify or get their state, how do we achieve it?

Firstly, we need to make one thing certain, each of the checkboxes must not have the same ID, I know this is probably a given but thought it was worth the mention!

Select All Checkbox Elements At Once

First, we need our HTML snippet with five checkbox elements that have been defined with a class of "myCheckboxClass".

HTML Example

<div style="margin:1em;">
  <div class="myCBWrapper">
    <input id="cb1" type="checkbox" class="myCheckboxClass" name="cb1">

    <input id="cb2" type="checkbox" class="myCheckboxClass" name="cb2">

    <input id="cb3" type="checkbox" class="myCheckboxClass" name="cb3">

    <input id="cb4" type="checkbox" class="myCheckboxClass" name="cb4">

    <input id="cb5" type="checkbox" class="myCheckboxClass" name="cb5">  
  </div>  
</div>

With our checkboxes defined in HTML, we need to utilize JQuery to select all checkbox elements at once.

JS

$('.myCheckboxClass');

And if we want to log this to the console, we can do the following –

console.log($('.myCheckboxClass'));

Which would output something like the following –

all checkboxes selected in the console

And that is it! We could then access the elements by using the numeric index of each checkbox that we want to modify.

Demo

Check out the following CodePen that uses all the checkboxes & JQuery together –

 

See the Pen
Selecting Checboxes
by Danny Englishby (@DanEnglishby)
on CodePen.

 

Summary

Achieving this task with JQuery is, as you can see, really straight forward. The moral of the story is, to make sure that all checkbox elements have some sort of matching identifier. Whether that be a class, data- attribute or similar.

SHARE ON

The Author: Dan Englishby

Select All Checkboxes With JQuery

You May Also Like

Leave a Reply

Your email address will not be published.