Stop form submission using JavaScript preventDefault() Event Method

In projects, it is often necessary to prevent form submission after clicking the submit button of an HTML form. So in this tutorial, we are going to see how to prevent or stop an HTML form from submitting even after clicking the form submit button.

To better understand let’s create an HTML form. Below is the code of our HTML form:

<form id="user-form" action="process.php" method="post">
  First name: <input type="text" name="first_name" id="first_name"><br/>
  Last name: <input type="text" name="last_name" id="last_name"><br/>
  Phone number: <input type="text" name="phone_number" id="phone_number"><br/>
  <input type="submit" id="submit-btn">

We have a submit button in the form which has the id “submit-btn”. Now if we click the button, the form will be submitted.

But suppose for some purpose we don’t want to let our form submitted. How can we do it? Is there any way to prevent the form from submission.

Immediately submit upload form after selecting file

Guess The Number Game Using JavaScript

Well, JavaScript has a method that can prevent the default action that belongs to the event. That means the default action will not occur. This is JavaScript preventDefault() event method which can stop the form submission.

Now we are going to prevent our form submission that we have just build using the preventDefault() event method of JavaScript. Below is our JavaScript code which can do this job:

document.getElementById("submit-btn").addEventListener("click", function(event){

In the above code, we have first applied the click event listener to the HTML form submission button. Inside the click event listener, we have applied the preventDefault() JavaScript method.

How to get value from input box in JavaScript?

That’s it. Now if we test our form on the browser, we will see that after clicking the form nothing has happened. Our form has not submitted. Now we can clearly say that we have prevented our form from submission using JavaScript preventDefault() method.

The supported browser of the preventDefault method is Chrome, Internet Explorer 9.0, Safari, Mozilla and opera.

So from this tutorial, we have learned how to prevent an HTML form submission using javaScript.

Leave a Reply

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