Forms are how users sign up, search, pay and talk to almost every web application.
A <form> groups controls and sends their values when submitted. Its action is the URL to send to and method is get (values in the query string; for searches and filters) or post (values in the request body; for anything that changes data).
Each control needs a name: only named controls are submitted, as name=value pairs. The common controls:
<input type="text">and its many types (email, password, number, checkbox, radio...),<textarea>for multi-line text,<select>with<option>elements for a choice list,<button>to submit.
Every control needs a label. Either wrap the control in <label> or connect them with for matching the control's id. A label is announced by screen readers, and clicking it focuses the control or toggles the checkbox, which makes small targets easier to hit. A placeholder is not a label: it disappears as soon as the user types.
Radio buttons that share a name form one group where only one can be selected; group related controls in a <fieldset> with a <legend> describing the question.
A <button> inside a form defaults to type="submit". For a button that should only run JavaScript, write type="button", or it will submit the form. Pressing Enter in a text field also submits the form.
Example
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label>
Password <input name="password" type="password" minlength="8" required>
</label>
<fieldset>
<legend>Plan</legend>
<label><input type="radio" name="plan" value="free" checked> Free</label>
<label><input type="radio" name="plan" value="pro"> Pro</label>
</fieldset>
<label><input type="checkbox" name="news" value="yes"> Send me news</label>
<button>Create account</button> <!-- type="submit" by default -->
</form>
<!-- Sends: email=...&password=...&plan=free (&news=yes only if checked) -->Remember
- Only controls with a name are submitted
- Every control needs a label (wrapping or for/id)
- method=get for reads, post for changes
- A button in a form submits unless type="button"
Watch out for
- Using placeholder text instead of a label.
- A plain <button> meant for JavaScript accidentally submitting the form.