How to use JavaScript to stop form submission?

Spread the love

Sometimes, we want to use JavaScript to stop form submission

In this article, we’ll look at how to use JavaScript to stop form submission.

How to use JavaScript to stop form submission?

To use JavaScript to stop form submission, we call e.preventDefault.

For instance, we write

<form>
  <!-- Your Input Elements -->
</form>

to add a form.

Then we write

document.querySelector("form").addEventListener("submit", (e) => {
  e.preventDefault();
  // ...
});

to select the form with querySelector.

Then we call addEventListener to listen to the submit event.

In the submit event handler, we call e.preventDefault to stop the default server side form submission behavior.

Conclusion

To use JavaScript to stop form submission, we call e.preventDefault.

Leave a Reply

Your email address will not be published.