There are two ways to submit a form from code, and the obvious one skips everything I care about. form.submit() sends the form without validation and without a submit event. requestSubmit() behaves like a click on the submit button.
// submit when the user presses Ctrl+Enter in the textarea
textarea.addEventListener("keydown", (event) => {
if (event.key === "Enter" && event.ctrlKey) {
form.requestSubmit();
}
});
// or act as if a specific button was pressed
form.requestSubmit(document.querySelector("#save-draft"));
With requestSubmit() the browser checks required, pattern and the other constraints and shows its error bubbles when something is wrong. If the form is valid, the submit event fires, so your handler that calls preventDefault() and sends the data with fetch still runs. With plain submit() that handler is skipped and the page simply navigates away.
You can pass a submit button as the argument. The browser then acts as if that button was pressed: its name and value are included and attributes like formaction apply. The button must belong to the form, or it throws.
Support: Chrome 76, Firefox 75 and Safari 16. Safari was late, so very old iPhones lack it; a fallback is to call click() on the submit button, which behaves almost the same.
Further reading: MDN: HTMLFormElement.requestSubmit()