Digital Ninja
Digital Ninja

Reputation: 3731

Semantic usage of the <label> in the form with radios

According to the HTML5 Doctor:

The label represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using for attribute, or by putting the form control inside the label element itself.

So putting this into a context with radio buttons. In an example of asking you to choose a favourite fruit in a form, if I were to say that the label "Apple" is the <label> for its radio button, to make the label clickable, I would put the radio control inside, such as:

<label>
   <input type="radio" name="fruit" value="apple"/> Apple
</label>

And since the <label> element in their example is also shown as the label for the entire input value, that shows my question "Your favourite fruit?" going into a label, thus making the whole section just full of labels?

<label>Your favourite fruit?</label>
<label>
    <input type="radio" name="fruit" value="apple"/> Apple
</label>
<label>
    <input type="radio" name="fruit" value="banana"/> Banana
</label>
<label>
    <input type="radio" name="fruit" value="watermelon"/> Watermelon
</label>

Is that correct?

And then also the for attribute on that first <label> that holds the question in their example refers to the id of the element. But I cannot do that since I have 3 elements, so that means it's impossible for me to use the for attribute?

Upvotes: 4

Views: 1518

Answers (1)

Lee Kowalkowski
Lee Kowalkowski

Reputation: 11751

The semantic way to tackle this would be to group the radio buttons with a fieldset element.

<fieldset>
    <legend>Your favourite fruit?</legend>
    <label>
        <input type="radio" name="fruit" value="apple"/> Apple
    </label>
    <label>
        <input type="radio" name="fruit" value="banana"/> Banana
    </label>
    <label>
        <input type="radio" name="fruit" value="watermelon"/> Watermelon
    </label>
</fieldset>

This approach to your scenario is recommended by the W3C's Accessibility Tutorials: https://www.w3.org/WAI/tutorials/forms/grouping/ and MDN's Fieldset Article: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset

The default rendering of fieldsets can be improved with CSS. One example of that is here https://design-system.service.gov.uk/components/radios/

Upvotes: 8

Related Questions