⊗jsSpFmFDI 240 of 281 menu

Working with FormData in JavaScript

Let's have some form:

<form action="/target/" method="POST"> <input name="test1" value="123"> <input name="test2" value="456"> <input type="submit"> </form>

Let's say we want to get the data of this form as key-value pairs. It is clear that for this we will have to run a loop and form what we want in it. In JavaScript, however, there is a simpler way - you can use the special FormData object, which allows you to get form data in an ordered form.

Let's take a look at how this object works. First, we get a reference to our form:

let form = document.querySelector('form');

Now let's create an object with our form:

let formData = new FormData(form);

We can output our object to the console, but with such an output we will not see the form data:

console.log(formData);

Let's convert our object to an array to see the form data:

console.log(Array.from(formData));

Given a form with three inputs. There is also a button. On button click, get the form data as an FormData object.

enru