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".
for
attribute is mainly a accessibility feature, relating a short description to a field. Also has functional uses, such as in checkbox: clicking its label also toggles its state. – Traducefor
andlabel
wrapping in HTML is strictly UI/UX feature. They have some a11y value as they establish association between input with some readable text. – Burleyfor
attribute is important for both UX and a11y cases. Not all browsers and screenreaders understandaria-*
attributes. See: w3.org/TR/WCAG20-TECHS/H44.html – Crossexamine