O'Reilly logo

Learning JavaScript by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Radio Buttons and Checkboxes

Both radio buttons and checkboxes provide one-click option choosing, usually among a smaller number of options than a selection. They differ in that radio buttons allow one, and only one, choice; you can check as many checkboxes as you like.

Both types of form-input elements are grouped by name. Here’s the syntax for a radio button:

<form name="someForm">
<input type="radio" value="Opt 1" name="radiogroup" />Option 1<br />
<input type="radio" value="Opt 2" name="radiogroup" />Option 2<br />
</form>

Notice that the name is the same for both options; that’s how the buttons are grouped. The checkbox syntax is exactly the same, except the type is set to checkbox rather than radio.

To access the selected items, use the same functionality as selection, except that you check to see if the item is checked rather than selected:

   var buttons = document.someForm.radiogroup;

   for (var i = 0; i < buttons.length; i++) {
      if (buttons[i].checked) {
         alert(buttons[i].value);
      }
   }

The only difference in processing between the two types is that the radio buttons have only one checked item.

It’s hard to screw up with radio or checkboxes, so JiT validation makes little sense. You could match the behavior of the buttons with other form options, but if you need to restrict one or more radio buttons or checkboxes, a better option would be to disable the option, rather than validate it post-event.

You can disable the option using the following JavaScript:

document.someForm.radiogroup[1].disabled=true; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required