mreq
mreq

Reputation: 6542

Does <label> for attribute has to be unique?

Can I have two labels with the same for value? Example:

<label for="foo">Outer label</label>
<div class="foo-bar">
    <input type="checkbox" id="foo" />
    <label for="foo">Inner label</label>
</div>

Upvotes: 3

Views: 2098

Answers (1)

David Thomas
David Thomas

Reputation: 253396

The for attribute links a control to an input, there is, so far as I know, no limit to the number of elements that can link to one input, so long as the id of that input (or textarea, select, etc) is unique.

For example, in the following demo both label elements will trigger the change (check/uncheck) of the checkbox input element:

<label for="foo">Outer label</label>
<div class="foo-bar">
    <input type="checkbox" type="checkbox" name="test" id="foo" />
    <label for="foo">Inner label</label>
</div>

JS Fiddle demo.

This can be useful for adding error messages (post-validation, for example) that explicitly link to, or otherwise identify, the element in which there's an error, without overriding/replacing the pre-existing label for that element.

Unfortunately there is, so far as I've yet found, no reference or documentation that explicitly allows an input (or similar element) to linked to only one control; however MDN's entry for <label> does state that:

The ID of a labelable form-related element in the same document as the label element. The first such element in the document with an ID matching the value of the for attribute is the labeled control for this label element.

Upvotes: 7

Related Questions