Skip to content

How to trigger a form submit from code

Maxim Zelenkin edited this page Jun 4, 2021 · 4 revisions

It turns out that .submit() is unreliable to use. See MDN's documentation of submit() (https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit), specifically, how it does not guarantee the onsubmit event handler to be triggered.

As far as using Web API, It's better to use the more recent dispatchEvent(), e.g.

form = document.querySelector('form');
form.dispatchEvent(new Event('submit', {bubbles: true})); 
// you can specify more options in `Event()` for reliability across different browsers.

Or use a convenient wrapper provided by rails-ujs.js:

form = document.querySelector('form');
Rails.fire(form, 'submit');

Write

import Rails from '@rails/ujs';
Rails.start();

If you don't know where the Rails constant comes from.

See https://github.com/rails/rails/issues/29546