Alternate Way for Adding Labels to Online Forms

To make HTML forms more accessible to those using assistive technology like screen readers, we need to use <label> tags to associate the field labels with the corresponding fields. It wasn't until recently that I realized you don't always need to add an id attribute to field that you're attaching the label to. There is another way and it requires less typing.

Background

Let's say we have a form field where visitors can type their name.

<input type="text" name="name" />

Adding a field label lets visitors know what they are expected to enter. My typical process for incorporating labels is to add an id attribute to the field.

<input type="text" name="name" id="name" />

Then the label is added and surrounded with the <label> tag. Note that the for attribute in the <label> tag needs to match the id attribute of the <input> tag.

<label for="name">Name:</label> <input type="text" name="name" id="name" />

Alternate Solution

Although the code works as expected, there is another way to write the code so the id and for attributes aren't needed. While looking through some documentation for the <label> tag, I noticed that you can associate a label with a field by just wrapping the <label> tag around the <input> tag.

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

Conclusion

In addition to being shorter, the alternative syntax for incorporating a field label limits the amount if id attributes used on the page. Having fewer ids will reduce the chance of accidentally using the same id twice. Note that id attributes need to be unique. In other words, the same value cannot be used twice on the same page.

Related Posts

0 Comments

There are currently no comments.

Leave a Comment