Forms

Forms are how users send information to a website: logging in, searching, signing up, checking out, leaving a comment. The <form> element wraps the controls, and each control's name decides how its value is sent. This lesson builds a complete form step by step.

A first form

Try it yourself
Result

Fill it in and press Send: the browser collects each field's name and value and sends them to the action URL (here, a test service that simply echoes back what it receives).

The form element

AttributePurpose
actionThe URL that receives the data. If omitted, the current page.
methodget (data in the URL) or post (data in the request body) — lesson 33
enctypeHow data is encoded; use multipart/form-data for file uploads
autocompleteon/off for the whole form
novalidateSkip the browser's built-in validation

name and value

Only controls with a name are submitted. The data arrives as name=value pairs:

TXT submitted data
name=Ana+Silva&email=ana%40example.com&message=Hello%21

Spaces become + and special characters are encoded, like @ as %40. The server reads each value by its name, so names should be short and consistent: email, first_name, quantity.

Labels

Every control needs a label that describes it. Connect them with for (on the label) matching id (on the control):

Try it yourself
Result

A connected label is announced by screen readers, and clicking it focuses the field or toggles the checkbox — a much bigger target, especially on touch screens. Wrapping the control inside the <label> (second example) also connects them. Lesson 29 goes further.

The main kinds of control

Try it yourself
Result
ElementForLesson
<input>Most single values — text, email, numbers, dates, checkboxes, radios, files…27
<select>Choosing from a list30
<textarea>Multi-line text30
<button>Submitting, resetting, or custom actions31
<fieldset> + <legend>Grouping related controls29

Radio buttons and checkboxes

Radio buttons sharing the same name form a group: only one can be chosen, and the selected one's value is sent. Checkboxes are independent; a checked box sends its value (on if no value is set), and an unchecked box sends nothing at all.

Forms and accessibility

  • Every control has a visible label — placeholder text isn't a substitute, because it disappears when you type.
  • Related controls (radio groups, address fields) are grouped in a fieldset with a legend.
  • Use the right input type, so phones show the right keyboard.
  • The form can be completed with the keyboard alone: Tab between fields, Space to toggle, Enter to submit.

Try it yourself

Add a "Phone" field (with a label) and a "How did you hear about us?" select menu to this form:

Try it yourself
Result