Clicking and checking checkboxes using Javascript

Posted by on November 28, 2011 in Javascript, Programming | 0 comments

Checkboxes are great tools for users because they allow for quick interaction with a form or page. Unlike dropdowns there’s only 1 click to get the desired result instead of 3. Also, for tablets, slates, smartphones and people with poor resolution monitors, checkboxes function alot easier than dropdowns that may require alot of scrolling.

Sometimes you may want to alter or check the state of whether checkboxes are checked already on your page. To simply see if they are checked, use the following code:

tempEle = document.getElementById(‘checkboxID’);
if(tempEle.checked == 1)
alert(‘checked off’);
alert(‘not checked’);

You may also want to have the checkbox be checked off then. Simply set the value of checked to equal 1 like so:

tempEle = document.getElementById(‘checkboxID’).checked = 1;

That won’t account for any onclick actions that you may have set on the checkboxes though. If you want to trigger those onclicks you’ll have to simulate it just as if the user clicked on the checkbox themselves. Use the code below. Notice that if the checkbox is already checked off, it will uncheck, so you may want to use the logic shown above to see if the checkbox is already checked off before using the click simulation.

tempEle = document.getElementById(‘checkboxID’).click();
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment

Your email address will not be published. Required fields are marked *