How to listen to the form submit event in JavaScript?

Sometimes, we want to listen to the form submit event in JavaScript.

In this article, we’ll look at how to listen to the form submit event in JavaScript.

How to listen to the form submit event in JavaScript?

To listen to the form submit event in JavaScript, we call addEventListener on the form.

For instance, we write

document.querySelector("#myForm").addEventListener("submit", (e) => {
  if (!isValid) {
    e.preventDefault();
  }
});

to select the form with

document.querySelector("#myForm")

Then we call addEventListener on it with 'submit' and a callback that runs when we submit the form.

In the callback, we check if isValid is false.

If it is, we call e.preventDefault to prevent the default server side form submission behavior and do what we want.

Conclusion

To listen to the form submit event in JavaScript, we call addEventListener on the form.