Categories
JavaScript Answers

How to prevent form from being submitted with JavaScript?

Spread the love

To prevent form from being submitted with JavaScript, we call preventDefault.

For instance, we add a form with

<form>
  <button type="submit">Submit</button>
</form>

Then we write

const element = document.querySelector("form");

element.addEventListener("submit", (event) => {
  event.preventDefault();
  //...
  console.log("Form submission cancelled.");
});

to select the form with querySelector.

And then we listen for the submit event on it with addEventListener.

In the submit handler, we call event.preventDefault to stop the default submit behavior.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *