How to Stop a Form Submit using JavaScript
Table of Contents
Forms are extremely essential to web development and the web as a whole.
They are the primary way for a website to ask for information that a user can then submit.
However, sometimes you don't want to submit a form because you want to do something else with the data.
In this post, we'll learn how you can stop a form submission using JavaScript.
How to Stop a Form Submission
Let's say you have a form that looks like this:
HTML<form action="/submission" method="POST" class="form">
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
This is a simple form that has a single field, name
, and a submit button.
Now, normally what would happen when you press the submit button is that the form would be submitted to the URL /submission
and the data would be sent to the server.
However, we can stop this from happening by using JavaScript.
First, let's add an event listener to this form and listen to the submit
event:
JAVASCRIPTconst form = document.querySelector(".form");
form.addEventListener("submit", event => {
// do something when the form is submitted
});
This method will now fire when that button is pressed.
To stop the form from submitting, we can just call the preventDefault()
method on the event object:
JAVASCRIPTconst form = document.querySelector(".form");
form.addEventListener("submit", event => {
event.preventDefault();
// do whatever you want instead of submitting
});
Now, the event will not be submitted and you can do whatever you want with the data afterwards.
Conclusion
In this post, we looked at how you can stop a form submission using JavaScript.
Simple add an event listener to the form and call the preventDefault()
method on the event object.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React