Sometimes, we want to stop form from refreshing page on submit with JavaScript.
In this article, we’ll look at how to stop form from refreshing page on submit with JavaScript.
How to stop form from refreshing page on submit with JavaScript?
To stop form from refreshing page on submit with JavaScript, we use the preventDefault
method.
For instance, we write
const form = document.getElementById("myForm");
const handleForm = (event) => {
event.preventDefault();
};
form.addEventListener("submit", handleForm);
to select the form with getElementById
.
Then we call event.preventDefault
in the handleForm
function to stop the form from submitting.
Finally we call addEventListener
with 'submit'
and handleForm
to add handleForm
as the submit event handler.
Conclusion
To stop form from refreshing page on submit with JavaScript, we use the preventDefault
method.