submit() vs. requestSubmit()

Last week I learned about the requestSubmit() event from the Workingdraft Podcast (German). You may already know about the submit() event which lets you programmatically submit a form, but did you know there is also an requestSubmit() event. In this article you will learn the difference between submit() and requestSubmit();

submit() #

<form action="/changename">
<label for="name">Name</label>
<input type="text" id="name" required>
</form>

<button>Change name</button>
const btn = document.querySelector('button');
const form = document.querySelector('form');

btn.addEventListener('click', function () {
form.submit();
})

As you can see the name input has a required attribute, the form will however still be submitted, because submit() doesn't care about validation.

requestSubmit() #

This is where requestSubmit() is useful. It acts exactly like a trigger on a submit button. If you use form.requestSubmit() instead of form.submit() the form will only be submitted if it is valid. If you leave the name input empty the browser will show a hint to the user that they have to fill out that field and the form will not be submitted.

Browser support is pretty good, except for Internet Explorer and more importantly Safari. So, you should make a feature detection before using it.

const form = document.querySelector("form");

if (form.requestSubmit) {
form.requestSubmit();
} else {
form.submit();
}

As the form will not be validated in Internet Explorer and Safari, you should, as always, validate also on the server-side.

This is not to be confused with the submit event. Unlike submit() it does handle validation and will only trigger if the form is valid.

Resources #

MDN: submit https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

MDN: requestSubmit https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit

requestSubmit offers a way to validate a form before submitting it https://www.stefanjudis.com/today-i-learned/requestsubmit-offers-a-way-to-validate-a-form-before-submitting-it/