Sometimes, we want to do something before on submit with JavaScript.
In this article, we’ll look at how to do something before on submit with JavaScript.
How to do something before on submit with JavaScript?
To do something before on submit with JavaScript, we call preventDefault
to stop the default submit action.
For instance, we write
<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
<input type="text" value="" />
<input type="submit" value="Submit" />
</form>
to add a form with the onsubmit
attribute set to prepareForm()
to call the prepareForm
function on form submission.
Then we write
function prepareForm(event) {
event.preventDefault();
// ...
document.getElementById("formId").requestSubmit();
}
to define the prepareForm
function that calls preventDefault
to stop the default submit action.
Then we do something before we call requestSubmit
to submit the form.
Conclusion
To do something before on submit with JavaScript, we call preventDefault
to stop the default submit action.