INCLUDE_DATA

Category javascript

Using JavaScript to validate one or more grouped checkboxes 16

Aug25

It’s a common task to validate a form with JavaScript upon form submission. And validating whether or not at least one checkbox in a checkbox group is checked is often a basic requirement of this task. But, if you’re form is created dynamically and if the number of checkboxes in a checkbox group can vary from 1 to more than 1, then the JavaScript needed to iterate over the checkboxes is slightly different.

Say you have an HTML form like this:

<form name="frm" method="post">
   <input type="checkbox" name="parts" value="1" />Head<br />
</form>

Then, using JavaScript, you can check whether the checkbox is checked like so:

var isChecked = document.frm.parts.checked;

Now, imagine that your form has more than one checkbox in the same checkbox group:

<form name="frm" method="post">
   <input type="checkbox" name="parts" value="1" />Head<br />
   <input type="checkbox" name="parts" value="2" />Neck<br />
   <input type="checkbox" name="parts" value="3" />Arm<br />
   <input type="checkbox" name="parts" value="4" />Leg<br />
</form>

Then, the JavaScript code changes a little bit, as now you have to iterate over each of the checkboxes.

var isChecked = false;

for (var i = 0; i < document.frm.parts.length; i++) {
   if (document.frm.parts[i].checked) {
      isChecked = true;
   }
}

But. if you tried using the 2nd chunk of JavaScript on the first chunk of HTML, you’ll get a JavaScript error. This is because if you only have one checkbox, there’ll be no array to iterate over. So, you need to do a quick check before hand to see if there is more than one checkbox. If so, then iterate; otherwise, don’t.

if (document.frm.parts) {
   if (typeof document.frm.parts.length != 'undefined') {
      for (i = 0; i < document.frm.parts.length; i++) {
         if (document.frm.parts[i].checked) {
            isChecked = true;
         }
      }
   } else {
      isChecked = document.frm.parts.checked;
   }
}

This code first checks to see that there exists at least one checkbox. Then, it checks whether the length attribute of the parts variable is defined or not. If it is defined, then we know there is more than one checkbox. Otherwise, there is only one.

And there ya have it!