Categories
JavaScript Answers

How to Listen to the Form Submit Event in JavaScript?

Spread the love

We can listen to the submit event of the form to watch for presses of the form submit button.

For instance, if we have the following form:

<form>
  <input type="text" name="name">
  <input type="submit" name="submit">
</form>

Then we can write:

const form = document.querySelector("form")
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const formData = new FormData(form)
  console.log(formData.entries())
});

to listen to the form submit event and get the data from the form with the FormData constructor.

We get the form with document.querySelector .

Then we call addEventListener on it with 'submit' as the first argument.

The 2nd argument of addEventListener is a callback that processes the form when it’s submitted.

In the callback, we call e.preventDefault() to stop the server-side form submission behavior.

Then we use the FormData constructor with the form element we selected to get its value.

And then we use the entries method to get the entered value.

It returns the iterator with the key-value pairs of the form values.

The key of each entry is the name attribute value of the field.

And the value is the value.

So if we entered ‘aaa’ into the text field, we get:

[
  [
    "name",
    "aaa"
  ]
]

as the result returned by entries .

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 *