Skip to content Skip to sidebar Skip to footer

How Do I Get Form Submit Event Listener To Work In Js?

I am replacing some jquery codes with vanilla js, and I am having trouble with the form submit event listener
.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 the form.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:

/* vanilla js replacement */
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");
})
<formname="myForm"><inputtype="text"name="name" /><buttontype="button">Click me</button></form>

The main downside to this method is that, unlike jQuery's .submit() method, requestSubmit() has weaker browser support.

Post a Comment for "How Do I Get Form Submit Event Listener To Work In Js?"