DEV Community

Cover image for JavaScript stop form submit
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript stop form submit

Forms are a very important part of building apps and websites. They are the key to user input.

Let's look at some examples of forms we can think of:

  • Login form
  • Subscribe to a newsletter
  • Feedback forms
  • Contact
  • Order
  • CMS system
  • Etc...

As you can see, forms are a big pillar in development.
And generally, a form will perform a specific type of request to a defined action.

<form action="post.php" method="POST"></form>
Enter fullscreen mode Exit fullscreen mode

Take the above example. It will perform a POST request to a file called post.php.

However, in modern development, we often want to keep the user on the page and do these transactions in the background by using JavaScript.

Think about a search bar, for instance, how annoying it would be if it had to refresh the page every time you change the search query.

That's where handling forms with JavaScript comes in super handy. Let's see how this works.

Handle form submits in JavaScript

To catch the form submit in JavaScript, we have to have the form available in our code.

The easiest way would be to add a selector. This could be a querySelector or fetch the form by its unique ID.

<form id="form-id">
  <input type="text" name="name" id="name-field" />

  <input type="submit" value="submit" />
</form>
Enter fullscreen mode Exit fullscreen mode
const form = document.querySelector('form');

const formId = document.getElementById('form-id');
Enter fullscreen mode Exit fullscreen mode

Both these methods will have the same reference to the form.

However, I would urge you to use the latter one since it's more unique especially if you can have more than one form on a page.

Let's take the ID method and handle the form submit in JavaScript to stop the submit.
For this to work, we need to attach an event listener on the form's submit action.

const form = document.getElementById('form-id');

form.addEventListener('submit', (event) => {
  alert('submitting');
});
Enter fullscreen mode Exit fullscreen mode

This will perform the following actions:

  • User clicks submit
  • Alert shows up
  • User dismisses alert
  • HTML form submit happens

That's not exactly what we want, as we want the HTML submit not to happen at all.

To intercept that behavior, we have to use the event.preventDefault code.

form.addEventListener('submit', (event) => {
  event.preventDefault();
  alert('submitting');
});
Enter fullscreen mode Exit fullscreen mode

Now we only get the alert, and our form is stopped!

You can check out the JavaScript form submit in this CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)