Sub topic 4
Buttons and how a form is submitted
This chapter assumes you can write a basic <form> with action and method, and that you know how name and value pairs make up submitted data. The JavaScript examples need only basic event handling. Here you will learn which button types exist, what happens between a click and the network request, and the failure modes that catch people out.
The three button types
A button's type decides what it does when activated.
| Type | Behavior inside a form |
|---|---|
| `submit` | Validates the form and submits it. This is the default. |
| `reset` | Restores every control to its initial value. |
| `button` | Does nothing by itself. It exists to run JavaScript. |
The default is the first gotcha. A <button> with no type attribute inside a form is a submit button. A "Show password" or "Add row" button that you forgot to mark type="button" will submit the form when clicked.
<form action="/search" method="get">
<label for="q">Search</label>
<input id="q" name="q" type="search">
<button type="submit">Search</button>
<button type="button" id="advanced">Advanced options</button>
</form>`<button>` versus `<input>`
You can create buttons with <input type="submit" value="Send"> or <button type="submit">Send</button>. They behave the same for submission. They differ in what they can contain:
<input>is a void element. Its label comes from thevalueattribute, and it can only be plain text.<button>has content, so it can hold an icon, a<span>, or formatted text.<input type="image" src="go.png" alt="Go">is a graphical submit button. It also submits the click coordinates asname.xandname.y. You will rarely need it.
Prefer <button>. With <input type="submit">, the value is both the visible label and the submitted value. With <button>, you can show one thing and send another.
What triggers a submission
A form is submitted in three ways:
- The user activates a submit button with a click, Enter, or Space.
- The user presses Enter in a text-like field. This is called implicit submission. The browser acts as if the form's default button had been clicked. The default button is the first submit button in tree order.
- Script calls
form.requestSubmit().
If the form has no submit button, implicit submission still works only when the form has a single field that accepts text. With two text fields and no submit button, Enter does nothing. Always include a real submit button.
The submission sequence
Once a submission is requested, the browser follows a fixed order.
The diagram follows below in the required form.
Three consequences follow from this order:
- The
submitevent fires only after built-in validation passes. Invalid forms never reach your handler. - The form data is built after the
submitevent. Changes a handler makes to control values ordisabledstate affect what is sent. - Calling
preventDefault()stops the navigation. Nothing is sent unless your script sends it.
Which button's value is sent
A submit button with a name contributes its name=value pair only when it is the button that triggered the submission. This lets one form offer several actions.
<form action="/posts/42" method="post">
<label for="body">Body</label>
<textarea id="body" name="body" required></textarea>
<button type="submit" name="action" value="publish">Publish</button>
<button type="submit" name="action" value="draft" formnovalidate>Save draft</button>
</form>Clicking Publish sends body=...&action=publish. Clicking Save draft sends action=draft. Pressing Enter in a field sends the first button's value, publish. Put the safest action first, because Enter will trigger it. A "Delete" button should never be the first submit button in a form.
Buttons with no name send nothing. A type="button" button never contributes data, because it is not a submit button.
Per-button overrides
A submit button can override the form's settings for its own submission.
| Attribute | Overrides | Example |
|---|---|---|
| `formaction` | `action` | `formaction="/preview"` |
| `formmethod` | `method` | `formmethod="get"` |
| `formenctype` | `enctype` | `formenctype="multipart/form-data"` |
| `formtarget` | `target` | `formtarget="_blank"` |
| `formnovalidate` | skips validation | `formnovalidate` |
formnovalidate is what makes the Save draft button above work. Without it, required on the textarea would block the draft save. You can set novalidate on the <form> to turn off built-in validation for every button.
Buttons outside the form
The form attribute links a control to a form by id, wherever the control sits in the document.
<form id="profile" action="/profile" method="post">
<label for="name">Name</label>
<input id="name" name="name" autocomplete="name">
</form>
<footer>
<button type="submit" form="profile">Save profile</button>
</footer>This helps when layout puts the button in a sticky footer or dialog toolbar. A button without a form attribute is associated with its nearest ancestor form. Forms cannot be nested in HTML, so use form="..." instead.
Disabled buttons
A disabled control can't be clicked or focused, and it is never submitted. Disabling the submit button until the form is valid looks tidy, but it hides the reason. A keyboard or screen reader user gets no feedback on what is wrong. Leave the button enabled and let validation explain the problem. Disable it only while a request is in flight.
Disabling the submitter inside a submit handler has a trap. If you let the native submission continue, the form data is built after your handler runs. A button you just disabled is dropped, along with its name=value pair. Use requestAnimationFrame or setTimeout to disable it after the data is built, or keep a flag and ignore repeat submissions.
Controlling submission from JavaScript
The submit event handler receives a SubmitEvent. Its submitter property is the button that triggered the submission. It is null when the submission came from requestSubmit() with no argument, or from some implicit submissions.
const form = document.querySelector('#post-form');
let sending = false;
form.addEventListener('submit', async (event) => {
event.preventDefault();
if (sending) return;
sending = true;
const submitter = event.submitter;
const data = new FormData(form, submitter);
const label = submitter?.textContent;
if (submitter) submitter.textContent = 'Sending…';
try {
const response = await fetch(form.action, {
method: form.method,
body: data,
});
if (!response.ok) throw new Error(`Server returned ${response.status}`);
} finally {
sending = false;
if (submitter) submitter.textContent = label;
}
});The second argument to new FormData(form, submitter) includes the submitter's name=value pair, which a plain new FormData(form) would leave out. Without it, the action=draft value from the earlier example would be lost.
Two methods look alike but differ:
form.requestSubmit(button)behaves like a real click. It runs validation, firessubmit, and then navigates unless prevented. The optional argument must be a submit button belonging to the form.form.submit()skips validation and does not fire thesubmitevent. Your handlers never run. Avoid it unless you want that.
document.querySelector('#save-shortcut').addEventListener('click', () => {
form.requestSubmit();
});Reset buttons
type="reset" returns controls to the values in the HTML (value, checked, selected), not to empty. Users click it by accident and lose their input, and it rarely helps. Leave it out unless you have a clear use. If you keep one, you can intercept the reset event and call preventDefault() to ask for confirmation.
Common errors
- A
<button>with notypesubmits the form. - The first submit button runs on Enter, even if it is a destructive action.
formnovalidateis missing on a "Save draft" or "Cancel" button, so validation blocks it.- A button's value is missing because it had no
name, or becausenew FormData(form)was called without the submitter. form.submit()is used whererequestSubmit()was meant, so validation is skipped.- A button is disabled in the
submithandler, so its value is dropped.
Exercise
A form has two text fields and <button name="action" value="save">Save</button> followed by <button type="button" name="action" value="cancel">Cancel</button>. The user types in a field and presses Enter. What does the browser send for action, and what would change if you swapped the order of the two buttons?
Show answer
It sends action=save. Enter triggers implicit submission through the first submit button, which is Save. The Cancel button is type="button", so it is never a submit button and never contributes data. If the order were swapped, the result would be the same, because Cancel is still not a submit button and Save is still the first one.
Exercise
Your submit handler calls event.preventDefault() and then new FormData(form). The server needs to know whether the user clicked "Publish" or "Save draft". What is the fix?
Show answer
Pass the submitter as the second argument: new FormData(form, event.submitter). A FormData built from the form alone does not include the clicked button's name=value pair.