Making a Search Form Accessible: label vs aria-label vs aria-labelledby

accessibility, forms, html, search

Solution

Best practice, arguably, is to use `<label>`. It provides a larger hit area and offers a visual label that does not go away when the field gets focus (which is what happens in your example).

Since designs sometimes visually hide the label text, there is not much benefit to using a `<label>` and completely hiding it. In that scenario, using `aria-label` is probably fine in the context of a search form.

`aria-labelledby` needs to point to the `id` of some text to act as a label, so if you are going to do it in this context then you might as well go back to using `<label>`.

For your submit button, the `alt` attribute is the correct thing to use, but be less verbose.

In your case, you can get away with this:

<input type="text" value="" placeholder="Search" aria-label="Search">
<input type="image" src="/searchbutton.gif" alt="Submit">

The `placeholder` does what you are trying to do by leaving a value in the field that you then clear out. A screen reader will announce the field as "Input, text, Search" and the button as "Button, search". Brief, actionable labels are best.

For other code samples and examples, I made an accessible search field that starts only as the icon (as requested by a client): http://codepen.io/aardrian/pen/bVQzJj

Problem

The current HTML for my search form looks like this: ``` <form action=“/search/” method="post"> <input onclick="this.value='';" type="text" name="searchquery" id="searchbox" value="Search this site” class="swap_value" /> <input type="image" src=“/images/searchbutton.gif" id="searchbutton" alt="" /> </form> ``` I would like to make the search form accessible. As I understand accessibility from W3.org: https://www.w3.org/WAI/tutorials/forms/labels/ and a11ymatters.com: http://www.a11ymatters.com/pattern/accessible-search/, I need to add a label which will not display visually, and give a description to the search button, like this: ``` <form action=“#” method="post"> <label class=“search-label” for=“search”>Search this site:</label> <input onclick="this.value='';" type="text" name="searchquery" id="searchbox" value="Search this site” class="swap_value" /> <input type="image" src=“/searchbutton.gif" id="searchbutton" alt=“Search Button“ /> </form> ``` With the added CSS: ``` .search-label { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } ``` The W3.org article says that you can use label, aria-label, or aria-labelledby to identify a form control, but it doesn't say which is the best practice. Does anyone know which one is preferred/best practice? And is the alt tag sufficient to identify my search button, or does that need a label, too? Thanks so much!

Original source