I am replacing some jquery codes with vanilla js, and I am having trouble with the form submit event listener
<!-- html -->
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
/* jquery code that works */
$myForm = $("form[name=myForm]")
$("form button").on("click", function(e){
$myForm.submit()
})
$myForm.on("submit", function(e){
e.preventDefault()
console.log("Submitting form")
})
/* vanilla js replacement */
myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function(){
myForm.submit()
})
myForm.addEventListener('submit',function(e){
e.preventDefault()
console.log("Submitting form")
})
In the vanilla js, the form submit event listener does not seem to be triggered when the form is submitted programmatically. How do I fix this?
A form's submit event listener won't be triggered when you use the .submit() method on the HTMLFormElement:
The submit event fires when the user clicks a submit button ( or
<input type="submit">) or presses Enter while editing a field (e.g.<input type="text">) in a form. The event is not sent to the form when calling theform.submit()method directly.- MDN
You can use the .requestSubmit() method instead, which does trigger the onsubmit event handler of the form and performs constraint validation on the form:
const myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function() {
myForm.requestSubmit();
})
myForm.addEventListener('submit', function(e) {
e.preventDefault()
console.log("Submitting form");
})
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
The main downside to this method is that, unlike jQuery's .submit() method, .requestSubmit() has weaker browser support, now with around 89% of major browsers supporting it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With