1. Home
  2. Computing & Technology
  3. JavaScript

Radio Button Validation

3. Button Labels

clr gif
Join the Discussion

Questions? Comments?

In order for the person filling out the form to have some idea of what each button in our radio button group does we need to provide descriptions for each button. The simplest way to do this is to provide a descriotion as text immediately following the button.

There are a couple of problems though with just using plain text.

  1. The text may be visually associated with the radio button but which text is associated with which button may not be obvious to everyone (particularly those who are listening to the page rather than reading it).
  2. The usual behaviour for text associated with radio buttons in most programs is that clicking on the associated text will select the button and unless we can actually associate the text with the button we can't get it to work that way.

To attach the text to the button so that it is obvious which text belongs to which radio button and also so that clicking on the text will select the button (at least in modern browsers) we need to make a further addition to the code for each button by surrounding the entire button and its associated text within a label.

Here is what the complete HTML for one of the buttons on our example form looks like:

<label for="r1"><input type="radio"
name="group1" id="r1" value="1" /> button one</label>

As the radio button with the id referred to in the for parameter of the label tag is actually contained within the tag itself, the for and id parameters are redundant in some browsers. There are browsers however that are not smart enough to recognise the nesting that will function correctly if these parameters are included so it is worth putting them in so as to maximize the number of browsers on which this code will function.

That completes the coding of the radio buttons themselves. The final step is to set up radio button validation using Javascript.

1 | 2 | 3 | 4
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.