Radio buttons have a similar function to drop-down menus, in the sense that they allow one selection from a range of possible answers. Generally speaking radio buttons are used when the range of possible answers is limited to two (e.g. male or female, black or white, etc). Drop-down menus are used when the range of answers is greater than two.
Radio buttons are also unique in the sense that radio buttons that are part of the same question share the same name
attribute value. Indeed without this shared quality they will not act as radio buttons at all.
If you are old enough, an easy way to remember the purpose of radio buttons is to recall old car radios:
HTML “radio buttons” are named after this interaction model: push one button, and the others pop out.
As another value of the type
attribute of the <input>
tag, radio button elements have no closing tag. (In XHTML, the form element needs to be closed with a /
inside the tag itself).
As an example of a set of radio buttons, let’s ask whether a site visitor is male or female. (As a general rule, this is a bad idea for a form, as gender is not a binary concept, but it makes for a useful, simple example.)
<label for="male" accesskey="m">Male</label>
<input type="radio" name="gender" value="male" id="male">
<label for="female" accesskey="f">Female</label>
<input type="radio" name="gender" value="female" id="female">
Radio buttons need a value
attribute, so that our script for form data (PHP, ASP, Perl, etc) knows which button has been selected. (Our script will receive gender = male or gender = female. They still need an id
attribute so that we can make the form accessible and usable by JavaScript. By playing around with the radio buttons you should find that selecting one turns the other off (if they don’t, you have given them different name
attribute values.)
It can also be useful to have one of these pre-selected: again, be aware you are making an assumption about your customer.
<label for="male" accesskey="m">Male</label>
<input type="radio" name="gender" value="male" id="male" checked>
<label for="female" accesskey="f">Female</label>
<input type="radio" name="gender" value="female" id="female">
Note that we are using label
for each radio
input. There is unfortunately no meta-label tag that we can use to wrap around a set of radio buttons. However, fieldset
can be nested, so within your existing form and field set you could place the following:
<fieldset>
<legend>What is your gender?</legend>
<label for="male" accesskey="m">Male</label>
<input type="radio" name="gender" value="male" id=male" checked>
<label for="female" accesskey="f">Female</label>
<input type="radio" name="gender" value="female" id=female">
</fieldset>
Photographs by That Chrysler Guy, licensed under Creative Commons
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.