Dialogs that behave like dialogs
Close dialogs with forms
Use form method="dialog" and submit-button values to close a dialog and report the user’s choice declaratively.
A dialog often ends with a small choice: Save or Cancel, Confirm or Keep editing. A form whose method is dialog can express that choice without a click handler for every closing button.
Submitting a method="dialog" form closes its containing dialog. The activated submit button’s value becomes dialog.returnValue, and no HTTP request is sent. Listen for the dialog’s close event once, then decide what the selected value means.
<dialog id="editor">
<form method="dialog">
<label>Title <input name="title" required></label>
<button value="cancel" formnovalidate>Cancel</button>
<button value="save">Save task</button>
</form>
</dialog>
<script>
const editor = document.querySelector("#editor")
editor.addEventListener("close", () => {
if (editor.returnValue === "save") console.log("save the task")
})
</script>
The Save button participates in constraint validation because the input is required. Cancel carries formnovalidate, so the user can leave without first satisfying a field they no longer want to submit. This small detail prevents a surprisingly common modal trap.
Closing the dialog is not the same as persisting application data. Read FormData, validate your own business rules, update the board, and send data to a server as separate steps. The Forms course covers that complete submission path.
Reset stale values deliberately. If Cancel should discard edits, call form.reset() after close or repopulate the form immediately before the next open. Otherwise the browser correctly keeps the controls’ current values and your reused editor appears to remember abandoned work.
Make the title empty and select Save: browser validation should keep the dialog open. Select Cancel: it should close immediately. Reopen and decide whether the old title should remain. Add a third button with value="draft" and prove the close handler can distinguish it without another button listener. If Cancel is blocked by validation, confirm it has formnovalidate and is a submit button inside the dialog-method form.
Lesson completed