Toggle All Checkboxes Using jQuery

Toggle All Checkboxes Using jQuery

March 8, 2013
Front End

I needed to perform a mundane task of going to a large number of pages, with a large number of check-boxes selected at random, and flipping them in the opposite order.

So if I had 3 check-boxes, out of which two were selected like this:

I would need to flip them so it would look like this:

Here is a Codepen to demonstrate how it works:

See the Pen Simple jQuery Code to Flip all Checkboxes by Alex (@akras14) on CodePen.

The 3 lines of code bellow, would allow me to do just that in the console window of chrome debugger tools.

$(':checkbox').each(function(){
   this.checked = !this.checked;
});

$(':checkbox') selects all check-boxes on the page

.each( iterate through each check-box and

this.checked = !this.checked; changes the status of each check-box to opposite of what it originally was.

Just another example of how powerful jQuery can be. Pretty cool stuff!

P.S You can’t use $ in WordPress, you have to use keyword jQuery instead.

jQuery(':checkbox').each(function(){
   this.checked = !this.checked;
});