Sub topic 2
Form controls and submission refresher
This chapter reviews how a form turns into an HTTP request. Later chapters add validation on top of this model, so it helps to know exactly which controls get submitted, which don't, and when the browser checks constraints.
It assumes you know basic HTML (forms, labels, inputs), basic CSS selectors, how to select elements and handle events in JavaScript, and that a form submission sends data to a server over HTTP.
What a form is
A <form> element groups controls and describes how to send them. Three attributes decide the request:
| Attribute | Purpose | Common values | Default |
|---|---|---|---|
| `action` | URL that receives the request | `/signup`, a full URL | The current page URL |
| `method` | HTTP method | `get`, `post` | `get` |
| `enctype` | How a POST body is encoded | `application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain` | `application/x-www-form-urlencoded` |
With method="get", the browser appends the fields to the URL as a query string. With method="post", the fields go in the request body. Use multipart/form-data whenever the form contains a file input.
A form with no action posts back to its own URL. A form with no method uses GET, which is a common cause of passwords ending up in a URL during early prototyping.
Form controls
A control is an element the user can use to supply a value. These are the ones you will validate most:
<input>in its many types:text,email,number,checkbox,radio,date,file,password,hidden, and others.<textarea>for multi-line text.<select>with<option>children for a choice from a list.<button>to submit, reset, or run script.<fieldset>and<legend>to group related controls. These are not submitted, but a disabled fieldset disables every control inside it.
Other elements, such as <output>, <object>, and custom form-associated elements, also take part in forms. This tutorial focuses on the list above.
Labels
Every visible control needs a label. A <label for="email"> points at the control with id="email". Clicking the label focuses the control, and screen readers announce the label when the control gets focus. You can also wrap the control inside the label, which makes for and id unnecessary.
Labels matter for validation too. Browser error bubbles and your own inline messages are much easier to understand when the field has a clear name. The accessible-errors chapter builds on this.
The `name` attribute decides what is sent
The browser builds the submission from name/value pairs. A control with no name attribute is never submitted, even if it has an id and a value. This is the most frequent reason a server receives an empty field.
The id serves a different purpose. It lets labels, CSS, and scripts find the element. Keep the two roles separate: name is for the server, id is for the page.
What gets submitted
Not every control contributes a pair. The rules are:
| Control state | Submitted? | Notes |
|---|---|---|
| Text-like input with a `name` | Yes | Sent even if empty, as `name=` |
| Unchecked checkbox or radio | No | The name is absent from the data |
| Checked checkbox without `value` | Yes | The value is `on` |
| Radio group | One pair | Radios sharing a `name` allow one choice |
| `<select>` | Yes | The value of the selected option, or its text if no `value` attribute exists |
| `<select multiple>` | One pair per selected option | Repeated names |
| `disabled` control | No | Also skips validation |
| `readonly` input | Yes | Skips validation too, but the user can't edit it |
| `<input type="hidden">` | Yes | Not shown to the user |
| `<button>` | Only the one that triggered the submit | Needs a `name` |
| File input | Yes, as a file part | Requires `multipart/form-data` for the file contents |
Two entries deserve attention. The difference between disabled and readonly surprises many developers: a disabled field is dropped from the submission, while a readonly field is sent. Also, because an unchecked checkbox sends nothing, a server can't distinguish "unchecked" from "field missing". Server code usually treats an absent name as false.
A worked form
This page contains one of each common control. It runs as written. Open it in a browser and look at the console when you submit.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form refresher</title>
</head>
<body>
<form id="profile" action="/profile" method="post">
<label for="name">Name</label>
<input id="name" name="name" type="text">
<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 for="country">Country</label>
<select id="country" name="country">
<option value="">Choose one</option>
<option value="de">Germany</option>
<option value="jp">Japan</option>
</select>
<label for="bio">Bio</label>
<textarea id="bio" name="bio" rows="3"></textarea>
<label><input type="checkbox" name="newsletter"> Send me news</label>
<input type="text" name="locked" value="fixed" disabled>
<input type="hidden" name="source" value="refresher">
<button type="submit" name="intent" value="save">Save</button>
</form>
<script>
const form = document.getElementById('profile');
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(form, event.submitter);
console.log(new URLSearchParams(data).toString());
});
</script>
</body>
</html>If you leave everything untouched and press Save, the console prints:
name=&plan=free&country=&bio=&source=refresher&intent=saveNotice what is missing: newsletter (unchecked) and locked (disabled). Notice what is present with an empty value: name, country, and bio. An empty string is still a value, which is why a server must check for emptiness rather than for presence.
The second argument to FormData, event.submitter, includes the button that was pressed. Without it, the intent pair is missing. The submitter argument is supported in current browsers. Check your support targets before depending on it.
Buttons
A <button> inside a form defaults to type="submit". A button meant only to run script, such as "Show password", must say type="button", or it will submit the form. This mistake is common and, once validation is in play, confusing: clicking the stray button triggers error bubbles on unrelated fields.
The three types are:
submit: starts the submission process.reset: restores every control to its initial value.button: does nothing by default.
A control can belong to a form without being inside it. Give the control a form="profile" attribute, using the form's id. This is useful when a layout forces a button into a different part of the page.
The submission sequence
Submission is a short pipeline, and validation sits in the middle of it. The order explains many surprises later in the tutorial.
Two consequences follow:
- When a constraint fails, the
submitevent never fires. Asubmithandler can't run its own error display for fields the browser has already blocked, unless the form opts out of built-in validation. - Validation is a gate before the event. That is why the example in a later chapter sets
form.noValidate = truewhen it wants its ownsubmithandler to produce the messages.
Ways to start a submission
Several actions submit a form, and they don't all behave the same:
- Clicking a submit button, or pressing Enter in a text field (implicit submission). Both validate and fire
submit. form.requestSubmit()acts like a click on a submit button. It validates and firessubmit. You can pass a button to name the submitter.form.submit()sends the form immediately. It does not validate, and it does not fire thesubmitevent.
const form = document.getElementById('profile');
// Runs validation and the submit event, like a user click.
form.requestSubmit();
// Skips both. Avoid this when you want constraints to apply.
form.submit();Prefer requestSubmit() in scripts. Reaching for submit() is a quiet way to bypass every rule you wrote.
Reading values in script
You will often read a form's data without sending it. Three options cover most cases:
field.valuereads a single control. For a checkbox, readchecked. For a file input, readfiles.form.elementsis a live collection of all form controls, including ones attached with theformattribute. You can index it bynameorid.new FormData(form)returns the same name/value pairs the browser would send, with the same rules about disabled and unchecked controls.
FormData is the better choice when you want to match what the server will see, for example when posting with fetch. If you pass it directly as the body, the browser sends multipart/form-data. If you convert it with URLSearchParams first, you get the URL-encoded format.
const form = document.getElementById('profile');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: form.method,
body: new URLSearchParams(new FormData(form)),
});
console.log(response.status);
});Why this matters for validation
The submission model sets up the rest of the tutorial:
- Only controls with a
namereach the server, so a server rule can only check what the form actually sends. - Disabled controls are skipped by both submission and validation. Disabling a field to "protect" it does not make its value trustworthy, and the field can be re-enabled in developer tools.
- Validation happens before the
submitevent, so you choose between letting the browser stop the submission and taking over withnovalidate. - Anything in a request can be forged. A client can send a POST with any fields at all, without ever loading your page.
Common errors
- Missing
name. The field appears on screen but is absent from the request. - Using
idfor the server. The server never sees ids. - Expecting unchecked checkboxes to send
false. They send nothing. - Using
disabledwherereadonlyis meant. The value is dropped from the submission. - Calling
form.submit()from a script. This skips validation and thesubmitevent. - Leaving out
enctype="multipart/form-data"on a file upload form. The server receives only file names. - Relying on the default
method. Forms default to GET, which puts values in the URL and the browser history.
Exercise
A form contains <input id="coupon" type="text"> and a checkbox <input type="checkbox" name="terms" id="terms"> that the user leaves unchecked. The user fills in the coupon field and submits. Which pairs does the server receive, and how would you fix the problem?
Show answer
The server receives neither field. The coupon input has no name, so it is not submitted. The unchecked terms checkbox is also omitted, because unchecked checkboxes send nothing. Fix the first by adding name="coupon". For the second, nothing needs fixing in the HTML. The server should treat a missing terms as false, and a rule that requires it should reject the request when the name is absent.
Exercise
Your script calls form.submit() after a custom check. Users report that invalid emails reach the server even though the input has type="email" and required. What is happening, and what should you call instead?
Show answer
form.submit() sends the form immediately, without running constraint validation and without firing the submit event. The type="email" and required rules are never evaluated. Call form.requestSubmit(), which behaves like a user clicking a submit button: it validates, fires submit, and shows the browser's error if a control is invalid.
Exercise
Which of these controls is sent to the server: a disabled text input with a value, a readonly text input with a value, or a hidden input with a value? Which of them are checked by built-in validation?
Show answer
The readonly input and the hidden input are sent. The disabled input is not. Disabled controls are also skipped by validation. Readonly inputs are barred from constraint validation as well, and hidden inputs have no constraints that apply. In practice, none of the three produce built-in validation errors.