brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: form.requestSubmit() submits from a script and still runs validation

Javascript
~/tips/tip-js-requestsubmit-validation

// submit when the user presses Ctrl+Enter in the textarea

Script-triggered submits check required fields and fire the submit event, unlike submit().

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()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link