Nathan Lafferty
Nathan Lafferty

Reputation: 2098

How should you structure HTML Label For attribute to work with screen readers and multiple forms

It is considered best-practice for label elements in HTML to use the for attribute to bind to an input element:

<div>
  <label for="myinput">My Input Label</label>
  <input id="myinput" type="text" />
</div>

Instead of

<label>
  My input Label
  <input type="text" />
</label

Due to accessibility & screen readers understanding the prior example better

Relevant 1

Relevant 2

However, Ids must (should) be unique for the entire document in html specification Relevant

Lets assume I want to make a form render on two different parts of my website. This means I cannot use the for attribute on the label because it requires an id to work correctly. How should I structure a form so that it can be duplicated in the document and still be understood by accessibility readers?

I am aware I could process the Ids on the label/input to guarantee they are unique. I am wondering if there is a solution that:

  1. Plays nice with screen readers
  2. Does not require for attribute on the label

Upvotes: 1

Views: 407

Answers (1)

aardrian
aardrian

Reputation: 9009

Unless you are supporting older screen reader / browser combinations you can wrap the label text and the field in one <label>. The examples referenced in the WCAG document you linked are 10 versions or more old, and the IE bug that did not honor wrapped <label>s went away in IE7 (I think, maybe earlier).

Be aware that there are potential styling differences depending on how you write your CSS as well as potential event bubbling issues depending on how you write your JS. But for pure HTML this is fine.

Remember that screen readers are not the only tools the benefit from the <label> element. Users with motor impairments benefit from the larger overall hit area. Users with low vision or cognitive impairments can benefit from browser default focus styles. On top of this, not all screen reader users are blind, so you want to make sure the experience for sighted users is analogous for those using screen readers.

So these should work for you (without knowing anything about the technology profile of your users):

<label>
 First Name:
 <input type="text">
</label>

and

<label>
 <input type="checkbox">
 Yes, please spam me.
</label>

Upvotes: 2

Related Questions