See https://www.w3.org/WAI/WCAG22/Techniques/failures/F68.html#tests
Procedure¶
For all input
, textarea
, and select
elements in the Web page (except inputs of type hidden
, submit
, reset
, or button
:
1. Check that each element has a programmatically determined name using one of the following ways:
1.1. […]
1.2. […]
1.3. the text label is contained in a label
element that is correctly associated to the respective input
element via the label's for
attribute (the id
given as value in the for
attribute matches the id
of the input element).
1.4. the control is contained within a label
element that also contains the label text.
1.5. […]
1.6. […]
So I'd say the following code should be 'QA successful' as of '1.4.' above:
<label>
Username
<input type="text" …>
</label>
We really get into trouble if we need to set unique id
attributes everywhere. As soon as a form is used twice on the same page, the id
isn't unique anymore.
The result of a non-unique id
is a wrong label-association. A wrong label-association is far worse than not providing the id
and for
attributes to 'improve' an already working label-to-input association.
Also see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
To explicitly associate a <label>
element with an <input>
element, you first need to add the id
attribute to the <input>
element. Next, you add the for
attribute to the <label>
element, where the value of for
is the same as the id
in the <input>
element.
Alternatively, you can nest the <input>
directly inside the <label>
, in which case the for
and id
attributes are not needed because the association is implicit:
<label>
Do you like peas?
<input type="checkbox" name="peas" />
</label>
And see (german): https://bitvtest.de/pruefschritt/bitv-20-web/bitv-20-web-9-1-3-1h-beschriftung-von-formularelementen-programmatisch-ermittelbar
Was wird geprüft?¶
Beschriftungen sollen über Markup mit den Formularelementen, die sie beschriften, verknüpft sein.
Bei label
-Elementen geschieht das über das for
-Attribut oder den Einschluss des beschrifteten Formularelements in das label
-Element. […]