Sub topic 6
Returning results with form method="dialog"
This chapter assumes you can open and close a <dialog> with showModal() and close(), and that you know the close event. It also assumes you know how HTML forms submit and validate. Here you will learn how a form inside a dialog can close it and report which button the user pressed, with no click handlers.
What method="dialog" does
A form normally has method="get" or method="post". Submitting it sends an HTTP request and navigates the page. A third value, method="dialog", does something different. When the form is submitted, the browser does these things:
- It runs constraint validation, the same as for any form.
- It fires the
submitevent. - It does not send a request and does not navigate.
- It closes the nearest ancestor
<dialog>. - It sets that dialog's
returnValueto thevalueof the button that submitted the form. - The dialog's
closeevent then fires.
The result is a simple pattern. Each button declares its outcome in the HTML, and one close listener reads it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rename project</title>
</head>
<body>
<button id="open" type="button">Rename project</button>
<p id="status">No change yet.</p>
<dialog id="dlg" aria-labelledby="dlg-title">
<form method="dialog">
<h2 id="dlg-title">Rename project</h2>
<label>Name <input name="name" required autofocus></label>
<menu>
<button value="save">Save</button>
<button value="cancel" formnovalidate>Cancel</button>
</menu>
</form>
</dialog>
<script>
const dlg = document.getElementById('dlg');
const form = dlg.querySelector('form');
const status = document.getElementById('status');
document.getElementById('open').addEventListener('click', () => {
dlg.returnValue = '';
form.reset();
dlg.showModal();
});
dlg.addEventListener('close', () => {
if (dlg.returnValue === 'save') {
const data = new FormData(form);
status.textContent = 'Renamed to ' + data.get('name');
} else {
status.textContent = 'No change (' + (dlg.returnValue || 'dismissed') + ').';
}
});
</script>
</body>
</html>The dialog has no open attribute in the markup, so it starts hidden. The Save button has no type, so it is a submit button. Its value becomes the returnValue. The Cancel button has formnovalidate, so it can close the dialog even when the required field is empty.
The sequence of events
The diagram shows what happens when the user presses Save.
Two details follow from this order. First, if validation fails, nothing after the first step happens. The browser shows its validation message and the dialog stays open. Second, submit fires before the dialog closes, so a submit handler can still stop the close.
Where the data lives
returnValue is only a string. It tells you which button was pressed, not what the user typed. A method="dialog" form never sends its field values anywhere, and the browser does not add them to returnValue.
You read the fields yourself with FormData. The form and its inputs are still in the DOM after the dialog closes, so you can do this in the close listener, as the example above does. The values are not cleared when the dialog closes. This is why the example calls form.reset() before reopening. Without it, the next opening would show the last text.
You can also read the value of a single field directly:
dlg.addEventListener('close', () => {
if (dlg.returnValue !== 'save') return;
const name = form.elements.name.value.trim();
console.log('Save with name:', name);
});Promise wrapper
The close event fires on every close, so wiring it up per call gets awkward. A small helper turns the dialog into something you can await:
function ask(dialog) {
return new Promise((resolve) => {
dialog.returnValue = '';
dialog.addEventListener(
'close',
() => resolve(dialog.returnValue),
{ once: true }
);
dialog.showModal();
});
}
document.getElementById('open').addEventListener('click', async () => {
const result = await ask(document.getElementById('dlg'));
if (result === 'save') {
console.log('User confirmed.');
} else {
console.log('User backed out.');
}
});{ once: true } removes the listener after it runs, so repeated opens do not stack up listeners. The promise resolves with an empty string when the user presses Escape, because Escape does not set a value.
How returnValue gets set, and when it does not
Several things can close a dialog. Only some of them set returnValue.
| How the dialog closes | returnValue afterwards |
|---|---|
| Submit button with a `value` attribute | That value |
| `dlg.close('text')` | `'text'` |
| `dlg.close()` with no argument | Unchanged from before |
| Escape key (modal dialog) | Unchanged from before |
| Submit button without a `value` attribute | Unchanged from before |
"Unchanged" is the source of most bugs with this feature. returnValue is not reset when you open the dialog. If the user pressed Save last time and presses Escape this time, returnValue still says "save", and your code will treat the dismissal as a confirmation.
Give every button in the form an explicit value, even when it seems redundant. That makes each outcome visible in your close listener.
Validation and formnovalidate
Constraint validation applies to method="dialog" forms the same way as to any other form. Attributes like required, pattern, minlength, and type="email" block a submit and show the browser's message. The dialog stays open and returnValue is not touched.
Buttons that must always work, such as Cancel, need formnovalidate. Without it, a user who opens the dialog and clicks Cancel with an empty required field sees "Please fill out this field" instead of the dialog closing.
An alternative is a Cancel button that is not a submit button at all:
<button type="button" onclick="this.closest('dialog').close('cancel')">Cancel</button>This avoids validation entirely. It also sidesteps the Enter-key problem described next.
The Enter key picks the first submit button
When a user presses Enter inside a text field, the browser performs implicit submission. It acts as if the form's default button had been clicked. The default button is the first submit button in tree order.
In the first example, Save comes before Cancel, so Enter saves. Many designs put Cancel on the left. If you write Cancel first in the markup, Enter inside the input now submits as Cancel, and with formnovalidate it closes the dialog with "cancel" and discards the input. That is a confusing failure to find.
You have two ways to keep Cancel visually first:
- Keep Save first in the HTML and reorder with CSS, for example
menu { display: flex; flex-direction: row-reverse; justify-content: flex-end; }. - Make Cancel a
type="button"as shown above, so it is never the default button.
Note that reordering with CSS changes the visual order but not the tab order. Tabbing reaches Save first. Decide whether that is acceptable for your dialog.
Intercepting the submit
Because submit fires before the close, a handler can inspect the data and cancel the close with preventDefault(). This suits checks that HTML attributes cannot express, such as a name that is only whitespace.
<dialog id="dlg" aria-labelledby="dlg-title">
<form method="dialog">
<h2 id="dlg-title">Rename project</h2>
<label>Name <input name="name" required autofocus></label>
<p id="error" role="alert"></p>
<menu>
<button value="save">Save</button>
<button value="cancel" formnovalidate>Cancel</button>
</menu>
</form>
</dialog>
<script>
const dlg = document.getElementById('dlg');
const form = dlg.querySelector('form');
const error = document.getElementById('error');
form.addEventListener('submit', (event) => {
if (event.submitter?.value !== 'save') return;
const name = new FormData(form).get('name').trim();
if (name === '') {
event.preventDefault();
error.textContent = 'Enter a name that is not just spaces.';
form.elements.name.focus();
} else {
error.textContent = '';
}
});
</script>event.submitter is the button that triggered the submit. It is null for a submit started from form.requestSubmit() with no argument, so the optional chaining ?. is needed. The handler returns early for Cancel, so Cancel is never blocked. When the handler calls preventDefault(), the dialog stays open and returnValue is not set.
If you need to wait on something asynchronous, such as a server check, call preventDefault() first, do the work, then close the dialog yourself with dlg.close('save').
Using a button outside the form
Two attributes let you apply the dialog behavior to individual buttons rather than the whole form.
A button with formmethod="dialog" overrides the form's method for that button only. This lets a normal post form include a "Close without saving" button that closes the surrounding dialog without sending anything:
<dialog id="dlg2" aria-label="Feedback">
<form method="post" action="/feedback">
<label>Message <textarea name="message" required></textarea></label>
<button>Send</button>
<button formmethod="dialog" value="skip" formnovalidate>Skip</button>
</form>
</dialog>A button can also belong to a form elsewhere in the document via its form="id" attribute. If the form with that id is not inside any dialog, nothing is closed.
Common errors
- Nothing happens on submit. The form is not inside a
<dialog>.method="dialog"closes the nearest ancestor dialog. With no ancestor dialog, the submit does nothing at all. - The page reloads. The
methodattribute is missing or misspelled, so the form falls back toget. Check formethod="dialog"and look at the URL for a query string. returnValueis an empty string. The user pressed Escape, or the button had novalue.returnValuehas a stale value. You did not reset it before opening.- Data from the last session reappears. Form fields keep their values. Call
form.reset()before reopening. - Cancel shows a validation message. Add
formnovalidateto that button, or make ittype="button". - Enter discards the input. Cancel is the first submit button in the DOM.
Exercise
A dialog contains <form method="dialog"> with a required text input, then <button value="cancel" formnovalidate>Cancel</button>, then <button value="ok">OK</button>. A user types text into the input and presses Enter. What is dialog.returnValue after the dialog closes, and how would you change the markup so that Enter confirms?
Show answer
It is "cancel". Enter triggers implicit submission through the form's default button, which is the first submit button in the DOM, and that is Cancel. Move OK before Cancel in the markup (and restore the visual order with CSS if needed), or change Cancel to type="button" so it is not a submit button.
Exercise
A user opens a dialog, presses OK (returnValue becomes "ok"), then later opens the same dialog again and presses Escape. Your close listener checks dlg.returnValue === 'ok' and runs the confirm action. What went wrong, and what is the fix?
Show answer
Escape does not set returnValue, and returnValue is not reset when the dialog opens, so the old value "ok" is still there. Set dlg.returnValue = '' right before each call to showModal(), and give Cancel or dismissal a value that your code treats as a non-confirmation.