Categories
JavaScript Answers

How to do something before on submit with JavaScript?

Spread the love

To do something before on submit with JavaScript, we call preventDefault in the submit handler.

For instance, we write

<form id="formId" action="/" method="POST" onsubmit="prepareForm(event)">
  <input type="text" value="" />
  <input type="submit" value="Submit" />
</form>

to add a form.

We set the onsubmit attribute to call the prepareForm function.

Then we write

function prepareForm(event) {
  event.preventDefault();
  // ...
  document.getElementById("formId").requestSubmit();
}

to define the prepareForm function.

In it, we call preventDefault to stop the default submit behavior.

And then we select the form with getElementByid and call requestSubmit to submit the form.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *