To intercept a form submit in JavaScript and prevent normal submission, we use the preventDefault
method.
For instance, we write
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
to add a form.
Then we write
const processForm = (e) => {
e.preventDefault();
};
const form = document.getElementById("my-form");
form.addEventListener("submit", processForm);
to select the form with getElementById
.
And we call addEventListener
to add a submit event handler to call processForm
when we submit the form.
In processForm
, we call e.preventDefault
to stop the default submit behavior.