Today I learned (well, technically, a few days ago, the week has been a lot), that the web platform supports a requestSubmit method. Since the beginning of time (or the beginning of JavaScript), we've been able to submit forms like so:

var myForm = document.getElementById('theform');

I intentionally used getElementById there as a reminder of what we had before jQuery. Given that, why do we need another method? Two important requests.

Reason the First #

When using submit, any validation of form fields is completely skipped. Consider this form:

<form method="post" id="theForm">
	<label for="name">Name</label>
	<input id="name" name="name" required>

	<label for="email">Email</label>
	<input id="email" name="email" type="email" required>

	<input type="submit">

I've got two fields, both required, with the second field using type email. If you hit submit, the form will stop itself from POSTing and show errors, but if you submit with JavaScript, that validation is completely ignored.

I added two more buttons to my HTML:

	<button id="testSubmit">Test submit()</button>
	<button id="testRequestSubmit">Test requestSubmit()</button>

And wrote some quick JavaScript to demo this:

const $form = document.querySelector('#theForm');

document.querySelector('#testSubmit').addEventListener('click', () => { $form.submit() });

document.querySelector('#testRequestSubmit').addEventListener('click', () => { $form.requestSubmit() });

Clicking the first button immediately shows that validation is ignored. Clicking either the main submit button in the form or the tester button shows validation working.

Screenshot showing validation being run on the first formfield

Reason the Second #

Not only is validation ignored with submit(), any submit handler on the form itself is completely ignored. I added this:

$form.addEventListener('submit', e => {
	console.log('submit fired on form');

And again, submit() ignores it and requestSubmit() runs it fine. I'm mostly sure I remember this aspect of submit(), but it's definitely been a while since I've thought about it.

Anyway, everyone loves the web platform. (Except Apple.) Here's a CodePen showing this in action if you want to see for yourself. (Which is 100% why most of my blog posts exist.)

See the Pen requestSubmit test by Raymond Camden (@cfjedimaster) on CodePen.