Grouped form controls

So, so many times I see this same mistake being made with form controls. I guess it may be a case of people just copying the idea, but please don’t do this and group your form controls where appropriate.

Check the following HTML:

<label for="the-span">The baby's gender was?</label>
<span id="the-span">
  <input id="male" type="radio" name="gender" />
  <label for="male">Male</label>
  <input id="female" type="radio" name="gender" />
  <label for="female">Female</label>
</span>

Now, I can kind of see why people think this is okay. You’ve hooked the label up to the span with the for and id attributes. However, it’s totally useless at associating the controls effectively. It’s even worse when you see how a screenreader like JAWS interprets this.

JAWS menu for radio buttons without a fieldset and legend

Now all you can tell from that is there are two radio buttons, one with the option of ‘Male’ and the other ‘Female. Also bear in mind this is a simple demo with only two inputs. The more ungrouped radio buttons and checkboxes you have the more it’s going to get nasty doing things this way.

Now check the following HTML:

<fieldset>
  <legend>The baby's gender was?</legend>
  <input id="male" type="radio" name="gender" />
  <label for="male">Male</label>
  <input id="female" type="radio" name="gender" />
  <label for="female">Female</label>
</fieldset>

Here we’re wrapping the associated labels and inputs inside a fieldset and using a legend within it where the original label was in my first example. This links the answers to the question in the legend. Then in the following screenshot we see the difference this makes to JAWS.

JAWS menu for radio buttons wrapped inside a fieldset with a legend

Now the radio buttons have context and we clearly know what the question is. If ¬†any of the specific radio buttons was checked it would also tell us. THIS is the way to group your related form controls. It’s about as much as effort as the wrong way and considerably better.

So again, please, please don’t use controls in a way that make no sense out of context. You can read more about this with examples on the W3C website – Providing a description for groups of form controls using fieldset and legend elements.