Search code examples
htmlaccessibilitysection508

If an element is wrapped by a label, does the label require the "for" attribute?


Say I have a set of radio <input>s. I'm not a caveman, so I know I need to associate <label> with those <input>s. I'm fond of wrapping the radio buttons within their corresponding labels, for reasons enumerated here.

So, for example:

<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <label><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you</label>
    <label><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive</label>
</fieldset>

This wrapping associates the corresponding radio button with the label. Do I also need to define the label's for attribute?

<fieldset>
    <legend>Should I provide a "for" attribute?</legend>
    <label for="define_the_for_attribute_yes"><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_yes" value="yes" />Yep, if you know what's good for you</label>
    <label for="define_the_for_attribute_no"><input type="radio" name="define_the_for_attribute" id="define_the_for_attribute_no" value="no" />Nah, that would be redundant and repetitive</label>
</fieldset>

As pointed out by @Peter, "The for attribute of the label element must refer to a form control" (see http://www.w3.org/TR/html-markup/label.html), but this could be read to mean "if you specify the optional for attribute, it must refer to a valid form control".


Solution

  • According to the HTML5 spec - "If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element's labeled control."

    http://www.w3.org/TR/html5/forms.html#category-label

    So basically, no it is not required as long as it is wrapping any of these elements: button, input (if the type attribute is not in the hidden state), keygen, meter, output, progress, select, or textarea