Handling On/Off Checkbox State with JavaScript and Ajax

This is a 1996 topic which remains relevant 20 years later. Checkboxes are old, but handling checkbox state can still be tricky. There are several ways to capture and send the on/off state of a checkbox with JavaScript and Ajax, but I’m going to show you the surefire way to do it.

We have an “Is Latin” checkbox on a client application based on NixMash Spring. It’s a funky little effect which will italicize the title if the terma are Latin, popular with the Medical Set. We also have a “Save and Continue” function in the Save button which sends the Post Data, including the “Is Latin” flag, to a Spring MVC endpoint with Ajax.

Our “Is Latin” checkbox uses Thymeleaf and Spring to display its state.

Our “Save” button is nothing special.

The gold of this post is in the savePost() function. The nugget of value is, in a phrase, USE THE DOM, LUKE!

Of the varied ways to check if a checkbox is checked after being unchecked and vice versa, the most consistent way to capture the on/off state of a Checkbox is to get the element by its DOM ID, in this case:

if (document.getElementById('isLatin').checked) {...}

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.