Forms: The Basics
Prerequisites: Semantic page layout
Forms collect information from visitors: a search box, a login, a contact form, a checkout. Here is a complete, small one:
<form action="/subscribe" method="post">
<label for="name">Your name</label>
<input id="name" name="name" type="text" autocomplete="name">
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<button type="submit">Subscribe</button>
</form>
The browser shows two labelled text boxes and a button. Pressing the button (or Enter in a text box) submits the form.
form
action— the URL that receives the data. A server program (in PHP, Python, Node.js, ...) handles it. Withoutaction, the form submits to the current page.method—get(the default) puts the data in the URL:/search?q=bread. Use it for searches and filters — things that are safe to bookmark and repeat.postsends the data in the request body. Use it for anything that changes data: sign-ups, orders, messages, and logins.
input and name
input is a void element. Its name is the key the server receives —
an input without a name is not submitted. If a visitor types "Ada"
and "ada@example.com" above, the server receives:
name=Ada&email=ada%40example.com
(Special characters like @ are percent-encoded. Our
URL Decoder turns that back into readable text.)
label
Every control needs a label. <label for="email"> connects to the
input with id="email":
- Screen readers announce "Email address, edit text" when the input gets focus.
- Clicking the label focuses the input (or ticks a checkbox) — a bigger target, great on phones.
You can also wrap the input inside the label, with no for/id needed:
<label>
Your name
<input name="name" type="text">
</label>
A placeholder is not a label: it disappears as soon as someone
types, is often low-contrast, and isn't reliably announced.
Search forms
<search>
<form action="/search" method="get">
<label for="q">Search recipes</label>
<input id="q" name="q" type="search">
<button>Search</button>
</form>
</search>
The search element marks a search landmark. It's newer (supported in
current Chrome, Edge, Firefox, and Safari since 2023); older browsers
simply treat it like a div, so it's safe to use.
Practice
Build a login form that posts to /login with a username field, a
password field (type="password"), and a "Log in" button. Give both
fields labels and autocomplete values (username,
current-password).
Show solution
<form action="/login" method="post">
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button type="submit">Log in</button>
</form>