HTML Tutorial / Connect Labels and Inputs Correctly

An input receives a user's value; a label tells the user what the field is for. A reliable explicit association gives the input an id and gives the label a matching for value.

Connect a label to an input

<form method="get">
  <label for="visitor-name">Name</label>
  <input id="visitor-name" name="name" type="text">
  <button type="submit">Check</button>
</form>

Place this code in an HTML file's body and open it in a browser. Clicking “Name” should focus the input. Merely placing the text next to a field does not automatically connect them. An id must be unique within the document; duplicate IDs can make a label target the wrong field.

Also press Tab to reach the field and check that the focused element is visible. The label is the control's name, not just decorative text. Assistive technology should be able to identify which field is focused.

Do id and name do the same job?

No. id identifies an element in the document and can link it to a label, fragment, or script. name is the key used when the form submits the value. Here, visitor-name is the label target, while name is the submission key. Inspect submitted names and request methods with the data-list exercise in Form Structure and GET vs. POST.

If clicking the label does nothing, compare for with id. If typing works but the submitted URL lacks the value, check name. You can change id="visitor-name" to id="person-name" as long as you update the label's for; name="name" can stay the same if the server still expects that key.

Repair a disconnected label

<!-- Incorrect: for matches name instead of id -->
<label for="full_name">Name</label>
<input id="person-name" name="full_name">

<!-- Correct: for matches the input id -->
<label for="person-name">Name</label>
<input id="person-name" name="full_name">

Test the fragments in separate files. In the corrected version, clicking Name should focus person-name, while the submitted key remains full_name. Do not combine the two examples in one document: doing so duplicates the ID and invalidates the comparison.

A placeholder is not a label

A placeholder offers a short hint or example and disappears as a user types. It cannot replace a persistent field name. Keep a visible label and add the example separately. For persistent instructions associated with a field, see Add Placeholder Text to Form Fields.

<label for="email">Email address</label>
<input id="email" name="email" type="email"
       placeholder="name@example.com">

Even if a design hides a label visually, the field still needs an accessible name. Checkbox and radio inputs can also be nested inside a label, as in <label><input type="checkbox" name="agree"> I agree</label>. Click the label text to verify that the checkbox changes state. Choose clear wording before adjusting appearance. See the MDN label reference for association methods.