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:
JAVASCRIPT
const 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:
JAVASCRIPT
const 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!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!