JavaScript Form Validation: At Least One Checkbox/Radio Button

Environment: JavaScript

Problem

I needed to validate that at least one checkbox or radio button was checked (selected) in an HTML form, without knowing whether there would be more than one. If I assumed that there would be an array, but only one checkbox or radio button existed, then it would not work. No array can be assumed, because the actual number of options will be dependent on data coming from a database, rather than a hard-coded form with a set number of options.

The Fix

Status: Fixed

In the following, replace myForm with the actual form and myCheckbox with the name of the form control being checked. If checking a radio button instead of a checkbox, change the alert (although a more custom alert is probably more sensible anyway, such as "select at least one style of beer").

var checkFound = false;
for (var counter=0; counter < myForm.length; counter++) {
   if ((myForm.elements[counter].name == "myCheckbox") && (myForm.elements[counter].checked == true)) {
      checkFound = true;
      }
   }
if (checkFound != true) {
   alert ("Please check at least one checkbox.");
   }


Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License

Post new comment

The content of this field is kept private and will not be shown publicly.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <img> <h4> <h5> <h6> <s> <u> <span>
  • Lines and paragraphs break automatically.
  • You may link to Gallery2 items on this site using a special syntax.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.

 





My Books