Check or Uncheck All Checkboxes with JavaScript

I was working on a form for a new MODX extra (SiteCheck) recently with a bunch of checkboxes, and I needed some buttons that triggered JavaScript code to check and uncheck all of them. I thought I’d share what I came up with.

The Form

Here’s a generic, shortened version of the form. I’ve made everything flush left so you can see more of it without scrolling.

Notice the code for the two buttons, Check All, and Clear All. Both contain an onClick event that calls the Javascript Code to check or uncheck the checkboxes, each with a different argument, when the user clicks on the button. The tricky thing is that I didn’t want to check or clear the "Verbose" checkbox with either button.

Here’s an oddly styled (thank you WordPress) view of the form as it appears on the page:

Select the tasks to be Performed

Check Resources

Check Snippets

Check Plugins

Verbose Output

The JS code is included on this page so the buttons should work, depending on the current mood of this platform.

The JavaScript code above simply finds input tags on the page, and if their name is my_form_tasks[], sets their checked attribute to the value of the checkEm variable, which you recall from the two buttons' onClick events is either true or false.

The code gets all input tags on the page, but it won't touch any of them unless they have that name, so it will ignore the "Verbose" checkbox and any other checkboxes that might be on the page. It might be slightly faster to get the form itself and look for the checkboxes in it, but this code is plenty fast enough. The browser will have tokenized and indexed the page, so getting all the input tags will be quite fast.

Getting the JavaScript into the Page

There are two ways to do this. One is to simply put the JS code into the page content between script tags (as I've done with this page). The other is to put the JS code in a file, usually somewhere in the MODX assets directory, and add this line to the top of the snippet that processes the form (or create another snippet with just this code):

$modx->regClientStartupScript(MODX_ASSETS_PATH . 'path/to/css/file');

The Placeholders

You might be wondering what those placeholder tags are for. They allow the checkbox settings to be sticky. Whenever the user returns to the form, the checkboxes will be set the same way they were the last time they visited the page.

I'll be explaining the technique for doing that in another article — stay tuned.