Labelled input
Learn how to pair <label> and <input> elements.
Pairing label and field
A form field usually has two parts: a label (<label>) and an input field (<input>). The label says what the field wants; the input is where the user types.
To bind them, you set the label's for attribute and the input's id attribute to the same value. Example: <label for="email">Email</label><input id="email">. Now clicking the label also focuses the field.
Matching id and for
The id attribute gives an element a unique name within the page. In a form, each <input> should have its own id. The <label>'s for attribute carries the same name.
Example: <label for="name">Your name</label> and <input id="name" name="name">. Here for and id share the value name; the two bind. name is the key sent to the server.
Exercise Write a labelled input
Add a <label> and an <input> to the form. The label text should be Your name. Set both for and id to name.
Show example solution
<form>
<label for="name">Your name</label>
<input id="name" name="name">
</form>
Test yourself
-
Which attribute binds a <label> to an <input>?
- for
- name
- value
- type
Show answer
for — Correct. The label's for attribute matches the input's id.
-
Write the label's opening
<____ for="email">Email</label> <input id="email">Show answer
<label for="email">Email</label> <input id="email"> -
Match each tag to its role
- for
- Binds label to input
- id
- Input's unique name
- <label>
- Field label
- <input>
- Single-line field