Skip to content

How to trigger a form submit from code

koen handekyn edited this page Aug 23, 2018 · 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 just use a convenient wrapper provided by rails-ujs.js:

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

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