Lesson 7
25 min
form, input, label, select: collect user information.
So far, your pages display content: the user reads, looks, clicks on links. Forms do the opposite: the user sends information to the site. Login, sign-up, search, orders, contact messages, surveys: almost every interaction on the web goes through a form.
It works in four steps: the user fills in the fields, clicks the submit button, the browser checks the validation constraints, then sends the data to the address specified in the form. What happens next (saving to a database, sending an email...) is the job of the server, written in another language. In HTML, you only deal with the visible part: building the form.
Forms let you collect information entered by the user. They are written with <form>, which contains different types of fields.
<form action="/send" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required />
<label for="email">Email:</label>
<input type="email" id="email" name="email" required />
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>
<button type="submit">Submit</button>
</form>
action specifies the URL where the form data will be sent.method defines how the data is sent: get (visible in the URL) or post (in the body of the request, for sensitive data).<label> linked via for/id improves accessibility: clicking the label activates the field.name attribute for its value to be sent to the server.With the get method, the entered data is added to the end of the address, as name=value pairs separated by the& character. If you search for "black cat" on a search engine, you will see, for example, a URL like this appear in the address bar:
https://www.example.com/search?q=black+cat&page=1With post, the data travels in the body of the request, invisible in the address. Here is how to choose:
Never use GET for a password
With get, the password would appear in plain text in the address bar, the browser history and the server logs. Always use post (and an HTTPS connection) for sensitive data.
Each field must have a label that tells the user what to enter. The link between the two is made by giving the label's for attribute the same value as the field's id attribute. There is also a second way of writing it, where the field is placed inside the label:
<!-- Way 1: association with for and id -->
<label for="first-name">First name:</label>
<input type="text" id="first-name" name="first-name" />
<!-- Way 2: field placed inside the label -->
<label>
City:
<input type="text" name="city" />
</label>The association brings three benefits: screen readers announce the label when the field receives focus, a click on the label places the cursor in the field (very handy on mobile, where small boxes are hard to hit), and the clickable area of checkboxes gets bigger. Be careful: the placeholder attribute never replaces a label, because it disappears as soon as the user starts typing.
HTML5 introduced many types of <input>, each with its own behavior and validation — sometimes even a different keyboard on mobile.
<input type="text" placeholder="Plain text" />
<input type="email" placeholder="name@example.com" />
<input type="password" placeholder="Password" />
<input type="number" min="0" max="120" />
<input type="date" />
<input type="tel" placeholder="06 12 34 56 78" />
<input type="url" placeholder="https://..." />
<input type="range" min="0" max="100" />
<input type="color" />
<input type="checkbox" id="terms" />
<label for="terms">I accept the terms</label>
<input type="radio" name="level" id="beginner" value="beginner" />
<label for="beginner">Beginner</label>
<input type="radio" name="level" id="advanced" value="advanced" />
<label for="advanced">Advanced</label>
Here is what each type concretely brings:
email — checks for the presence of an "@" and displays a suitable keyboard on phones.password — masks the characters entered with dots.number — only accepts digits and offers arrows to increase or decrease the value.date — opens a calendar to pick a date.tel — displays the numeric keypad on mobile, without checking the format of the number.checkbox — a box you check or uncheck, independently of the others.radio — a single choice among several; the buttons of the same group share the same name.When several fields answer the same question, you group them in a <fieldset> tag with a <legend> title. Screen readers then announce the question before each answer.
<fieldset>
<legend>What is your HTML level?</legend>
<input type="radio" name="level" id="n1" value="beginner" checked />
<label for="n1">Beginner</label>
<input type="radio" name="level" id="n2" value="intermediate" />
<label for="n2">Intermediate</label>
<input type="radio" name="level" id="n3" value="advanced" />
<label for="n3">Advanced</label>
</fieldset>
<fieldset>
<legend>Which languages do you want to learn?</legend>
<input type="checkbox" name="languages" id="l1" value="css" />
<label for="l1">CSS</label>
<input type="checkbox" name="languages" id="l2" value="js" />
<label for="l2">JavaScript</label>
</fieldset>name: checking one automatically unchecks the others. The value attribute indicates the value sent to the server.name, but you can check several of them.checked attribute checks a choice by default.In addition to type, name andid, fields accept several attributes that make typing more comfortable:
<input type="text" name="country" value="Madagascar" />
<input type="text" name="username" placeholder="E.g. kelly42" autofocus />
<input type="email" name="email" autocomplete="email" />
<input type="text" name="reference" value="A-1042" readonly />
<input type="text" name="code" value="Unavailable" disabled />value — value pre-filled in the field.placeholder — a grayed-out example that disappears when typing (a hint, not a label).autofocus — places the cursor in this field as soon as the page loads; use sparingly.autocomplete — helps the browser automatically fill in the field with the user's saved information.readonly — the value is visible and sent, but cannot be edited.disabled — the field is grayed out, unusable, and its value is not sent.For a multi-line message, you use <textarea>rather than an <input>. Unlike the latter, it has a closing tag, and its initial content goes between the two tags, not in a value attribute.
<label for="comment">Your comment:</label>
<textarea
id="comment"
name="comment"
rows="5"
cols="40"
maxlength="500"
placeholder="Write your message here..."
>Pre-filled text, editable by the user.</textarea>The <select> tag creates a drop-down menu, where each option is an <option> tag.
<label for="subject">Topic:</label>
<select id="subject" name="subject">
<option value="">-- Choose a topic --</option>
<option value="quote">Quote request</option>
<option value="support">Technical support</option>
<option value="other">Other</option>
</select>
The text displayed between the <option> tags is what the user sees, whereas the value attribute is what is actually sent to the server. These two pieces of information can be different. Here are a few variants:
<select name="country" id="country">
<optgroup label="Africa">
<option value="mg" selected>Madagascar</option>
<option value="mu">Mauritius</option>
</optgroup>
<optgroup label="Europe">
<option value="fr">France</option>
<option value="be">Belgium</option>
</optgroup>
</select>
<select name="skills" id="skills" multiple size="3">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="js">JavaScript</option>
</select>selected — preselects an option.<optgroup> — groups options under a heading.multiple — allows selecting several options (with the Ctrl or Cmd key); size sets the number of visible rows.If you want to offer suggestions while still letting the user type something else, link a text field to a <datalist> tag with the list attribute:
<label for="city">City:</label>
<input type="text" id="city" name="city" list="cities" />
<datalist id="cities">
<option value="Antananarivo"></option>
<option value="Toamasina"></option>
<option value="Antsirabe"></option>
<option value="Mahajanga"></option>
</datalist>The <button> tag has a type attribute that determines its role. Forgetting to specify it is a classic source of bugs, because the default value inside a form is submit.
<button type="submit">Submit the form</button>
<button type="reset">Clear the fields</button>
<button type="button">Does nothing on its own</button>submit — sends the form.reset — puts all fields back to their initial value (use rarely: an accidental click erases everything).button — triggers no action by itself; you will use it with JavaScript.To allow a file to be uploaded (profile picture, document), you use type="file". You must then use the post method and add the enctype="multipart/form-data" attribute to the form, otherwise only the file name would be sent, not its content.
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="photo">Profile picture:</label>
<input type="file" id="photo" name="photo" accept="image/*" />
<input type="hidden" name="source" value="profile-page" />
<button type="submit">Send</button>
</form>The accept attribute filters the file types offered in the selection window. As for the type="hidden" field, it is invisible to the user but still sends its value to the server: handy for passing technical information. But never put confidential data in it, because anyone can see it by inspecting the page.
HTML lets you validate fields without writing a single line of JavaScript, thanks to validation attributes.
<input type="text" required minlength="3" maxlength="20" />
<input type="number" min="18" max="99" required />
<input type="email" required />
<input type="text" pattern="[0-9]{5}" title="5-digit postal code" />required prevents the form from being submitted if the field is empty.minlength / maxlength constrain the length of the entered text.min / max constrain a numeric value or a date.pattern imposes a custom regular expression (e.g. postal code format).When a constraint is not met, the browser blocks the submission, highlights the first faulty field and displays a message (in the user's language). In the pattern example above, [0-9] means "a digit", and the part in curly braces indicates repetition: exactly five digits. The title attribute completes the error message to explain the expected format.
Disabling validation (for your tests)
While experimenting, you can add the novalidateattribute to the <form> tag so that the browser ignores the constraints. Remember to remove it afterwards. On the styling side, CSS offers the :valid and :invalid pseudo-classes to color a field according to its state.
Good to know
Native HTML validation is useful for user comfort, but it can easily be bypassed (developer tools, direct requests). It never replaces server-side validation.
Now let's bring together the concepts of this lesson in a realistic form. Take the time to identify each element: the labels, the field types, the groups and the constraints.
<form action="/signup" method="post">
<h2>Create an account</h2>
<label for="name">Full name:</label>
<input type="text" id="name" name="name" required minlength="2" autocomplete="name" />
<label for="mail">Email address:</label>
<input type="email" id="mail" name="email" required autocomplete="email" />
<label for="pwd">Password (8 characters minimum):</label>
<input type="password" id="pwd" name="password" required minlength="8" />
<label for="birthdate">Date of birth:</label>
<input type="date" id="birthdate" name="birthdate" />
<fieldset>
<legend>Your HTML level:</legend>
<input type="radio" name="level" id="lvl1" value="beginner" checked />
<label for="lvl1">Beginner</label>
<input type="radio" name="level" id="lvl2" value="advanced" />
<label for="lvl2">Advanced</label>
</fieldset>
<label for="goal">Your goal:</label>
<textarea id="goal" name="goal" rows="3"></textarea>
<input type="checkbox" id="terms" name="terms" required />
<label for="terms">I accept the terms of use</label>
<button type="submit">Create my account</button>
</form>for and id.email, tel, date...): the browser helps you validate and adapts the mobile keyboard.autocomplete attribute on common fields (name, email, address) to make typing easier.name attribute: the field displays normally, but its value is never sent.for that doesn't match any id (a typo is enough): the label no longer works.id to several elements: an identifier must be unique within the page.name to each radio button of the same group: they no longer exclude each other.placeholder, which makes the form unusable with a screen reader.<button> tags without a type in a form: they submit the form without warning.form (with action and method), fields, and a submit buttonname to be sent and an associatedlabel to be understoodget for searches, post for data that modifies things or is sensitivetype of field; use select, textarea, fieldset and datalist when they fit betterrequired, min, max, minlengthand pattern attributes validate in the browser, never in place of the serverExercise
select) and a submit button.Going further
tel, and constrain the name field to a minimum length of 2 characters with minlength.Challenge: a complete sign-up form
<fieldset> with a <legend> (for example the choice of a workshop), a city field with suggestions using <datalist>, a "Comments" text area limited to 300 characters, and a submit button. Check that each label is properly associated with its field by clicking on it, then deliberately test the constraints by leaving fields empty or entering wrong values.