HTML course menu
HTML Forms: form, input, label, action, method and name Explained
Learn how HTML forms work: the form element, action and method (GET vs POST), input fields and the name attribute, labels, submit buttons, and what the browser sends to the server when a form is submitted.
On this page
Forms are how websites collect information: search boxes, sign-up pages, checkout pages, comment boxes. HTML provides the fields and buttons; a server (or JavaScript) handles the submitted data.
A first form#
<form action="/search" method="get">
<label for="query">Search courses</label>
<input type="text" id="query" name="q">
<button type="submit">Search</button>
</form>Type something and press Search. Below the form, the result box shows what the browser would send.
The parts of a form#
The name attribute#
Only fields with a name are submitted. The browser sends each field as a name=value pair:
<form action="/signup" method="post">
<p>
<label for="full-name">Full name</label>
<input type="text" id="full-name" name="fullName">
</p>
<p>
<label for="email">Email</label>
<input type="email" id="email" name="email">
</p>
<p>
<label for="nickname">Nickname (not sent, it has no name)</label>
<input type="text" id="nickname">
</p>
<button type="submit">Sign up</button>
</form>Fill in all three fields and submit: only fullName and email appear in the result.
GET versus POST#
With GET, the earlier search form would load /search?q=html+forms. Never use GET for passwords or personal information: URLs are saved in browser history and server logs.
Labels#
Every field needs a label. Connect them by giving the <label> a for attribute that matches the field's id. Then:
- screen readers announce the label when the field is focused;
- clicking the label focuses the field (or ticks a checkbox), which gives a bigger target to tap.
Labels are covered in depth in Labels, Fieldsets and Legends.
Who handles the data?#
HTML only builds the form and sends the data. Something else must receive it:
- A server-side program (written in Python, Java, Node.js, PHP and so on) reads the
name=valuepairs, checks them again, and saves them or sends emails. - JavaScript in the page can intercept the submission and send the data in the background (see the JavaScript course).
Browsers check fields before submitting (see Form Validation), but users can bypass that, so the server must always validate data too.
Practice#
Practice exercise
Build a newsletter form that posts to /subscribe with a labelled email field named email, a labelled text field named city, and a submit button "Subscribe". Submit it in the preview and check what would be sent.
Show solution
<form action="/subscribe" method="post">
<p>
<label for="sub-email">Email</label>
<input type="email" id="sub-email" name="email">
</p>
<p>
<label for="sub-city">City</label>
<input type="text" id="sub-city" name="city">
</p>
<button type="submit">Subscribe</button>
</form>Key takeaway#
Finished this lesson?