Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

336 LESSON 12: Designing Forms


Creating Radio Buttons


Radio buttons, which generally appear in groups, are designed so that when one but-
ton in the group is selected, the other buttons in the group are automatically unselected.
They enable you to provide users with a list of options from which only one option can
be selected. To create a radio button, set the type attribute of an <input> tag to radio.
To create a radio button group, set the name attributes of all the fields in the group to the
same value, as shown in Figure 12.13. To create a radio button group with three options,
the following code is used:

Input ▼
<p>Select a color:</p>
<label style="display: block;"><input type="radio" name="color" value="red">
Red</label>
<label style="display: block;"><input type="radio" name="color" value="blue">
Blue</label>
<label style="display: block;"><input type="radio" name="color" value="green">
Green</label>

Output ▼


I’ve used the same <label> technique here that I did in the check box example. Placing
the radio buttons inside the labels makes the labels clickable as well as the radio buttons
themselves. I’ve changed the display property for the labels to block so that each radio
button appears on a different line. Ordinarily I’d apply that style using a style sheet; I
used the style attributes to include the styles within the example.
As with check boxes, if you want a radio button to be selec ted by default when the form
is displayed, use the checked attribute. One point of confusion is that even though brows-
ers prevent users from having more than one member of a radio button group selected at
once, they don’t prevent you from setting more than one member of a group as checked
by default. You should avoid doing so yourself.

FIGURE 12.13
A group of radio
buttons.
Free download pdf