Can an input field have two labels?

[亡魂溺海] 提交于 2019-11-28 05:35:44

I assume this question is about HTML forms. From the specification:

The LABEL element may be used to attach information to controls. Each LABEL element is associated with exactly one form control.

Thus, each form control can be referenced by multiple labels, but each label can only reference one control. So if it makes sense to have a second label for a control (and in the situation you describe, it does) feel free to add a second label.

The HTML is legal, and it works (clicking on any of the labels will transfer focus to the field in question).

It's a little trickier to do right for accessibility reasons.

It's not a "common" approach, and because of that at least one common screen reader (I tested with NVDA) only reads the first label when you shift focus into the field -- it ignores any additional labels for the same field.

So if your error message is at the top of the page, a blind or low-vision user tabbing through the fields will hear just the error message when landing on the field in question, not the "real" label next to it.

Hence -- if you phrase the error message properly, that might be a good thing (certainly better than just highlight the non-validating field in red!).

Yes, you can have multiple labels point at the same form control. This is perfectly legal:

<label for="fname">First name</label>
<label for="fname">Enter your info</label>
<label for="fname">Why not a third label</label>
<input type="text" id="fname" name="fname">

This is just an example... normally you would wrap these lines with one label since they're close.

Although the way you show is legal, I think the better way to associate multiple labels with a single <input> element is to use the aria-labelledby attribute.

You first give unique id attributes to the <label> elements. You then place an aria-labelledby attribute on the <input> element, setting its value to the id values from the <label> elements, separated by a space.

Here is the example from the "Using the aria-labelledby attribute" page in the MDN web docs:

<div id="billing">Billing</div>

<div>
    <div id="name">Name</div>
    <input type="text" aria-labelledby="billing name"/>
</div>
<div>
    <div id="address">Address</div>
    <input type="text" aria-labelledby="billing address"/>
</div>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!