Forms
Forms and labels
Goal: Build a form with labelled fields and a submit button · 10 min
A <form> collects input and sends it to a server: action is the target URL, method is GET (data in the URL, for searches) or POST (data in the request body, for sign-ups and orders).
Each field needs a name (the key sent to the server) and a label:
<label for="email">E-mail</label>
<input id="email" name="email" type="email">
The label's for matches the input's id. Clicking the label focuses the field, and screen readers announce it. Other controls: <textarea>, <select> with <option>, checkboxes and radio buttons (group them with <fieldset> and <legend>). Submit with <button type="submit">.
Worked example: Newsletter form
- POST because it changes data on the server.
- Label linked to the input via for/id.
- Radio buttons grouped in a fieldset with a legend.
<form action="/subscribe" method="post">
<label for="mail">E-mail</label>
<input id="mail" name="mail" type="email">
<fieldset>
<legend>Frequency</legend>
<label><input type="radio" name="freq" value="weekly"> weekly</label>
<label><input type="radio" name="freq" value="monthly"> monthly</label>
</fieldset>
<button type="submit">Subscribe</button>
</form>