Reputation: 105
I would like to submit a form with vanilla JS, but still trigger submit events. Basically the same as pressing the "submit" button.
HTMLFormElement.submit()
skips the "submit" event so it does not work for me.
HTMLFormElement.requestSubmit()
seems like it would do what I want, but it's browser support is very poor. I would like Chrome/Safari/Firefox/Edge support.
Upvotes: 4
Views: 4184
Reputation: 43895
To programmatically submit a form and still trigger a "submit" event, besides using .requestSubmit()
, would be to use .click()
method on the "submit" button. In the example below are the following:
A <form>
that will post it's data to a live test server. The test server's response will be displayed in an <iframe>
located after the <form>
.
A <button>
outside of the <form>
and has no form
attribute assigned to it either. This button is isolated from the <form>
but it will still trigger a "submit" event indirectly since it is registered to the "click" event and the event handler will programmatically click the "submit" button.
Note, the <button>
is not necessary to use the .click()
method, it can be invoked by other means like any other method or function.
Click the Trigger button
<button class='trigger'>Trigger</button>
const trigger = document.querySelector('.trigger');
trigger.onclick = e => document.querySelector('form button').click();
.trigger {
vertical-align: top
}
<form id='UI' action='https://httpbin.org/post' method='POST' target='response'>
<fieldset>
<legend>Programmatically Submit a Form</legend>
<input name='test' value='TEST'>
<button name='send'>Send</button>
</fieldset>
</form>
<hr>
<button class='trigger'>Trigger</button>
<iframe name='response'></iframe>
Upvotes: 3