← Web basics: HTML, CSS and JavaScript

Forms and labels

Collect information with form, input and label.

Start this lesson

Forms let people send information: sign-ups, searches, orders. A <form> wraps the fields. The most common field is <input>, a box people type into (it has no closing tag). Every input needs a <label> that says what to type. Connect them by giving the input an id and the label a matching for attribute. Then clicking the label puts the cursor in the box, and screen readers read the label when the box is focused. The name attribute is the key the data is sent under.

<form>
  <label for="city">Your city</label>
  <input id="city" name="city">

  <label for="guests">Number of guests</label>
  <input id="guests" name="guests" type="number">
</form>

for="city" matches id="city", so the two belong together. When the form is sent, the typed values travel as city=... and guests=...

You can also wrap the input inside the label: <label>Your city <input name="city"></label>. That links them without needing for and id.

Placeholder text inside a box is not a label: it disappears when people start typing, and many screen readers skip it.