DEV Community

Cover image for How to use the FormData object
Jay Cruz
Jay Cruz

Posted on

How to use the FormData object

An explanation of what the FormData object is and how to use it with an existing HTML form.

What is a FormData object?

To understand what FormData objects are we should first know where they come from. The FormData objects are constructed from the FormData interface. This FormData interface gives us the ability to create key, value pairs with the FormData constructor to represent our form’s fields and values.

Using FormData in JavaScript

To demonstrate how to implement the FormData object with Javascript we’ll be using this form for our example.

Newsletter form

Let’s check out what the HTML looks like for this newsletter form.

One thing to notice here is that we’ve included the name attribute. This is important not to forget because only input fields containing the name attribute will work with the FormData object.

Now that we see how the form is set up let’s head over to our javascript file and code everything out.

Here you can see how we’re first listening for our form to be submitted. Once the submit event is triggered we create a new instance of the FormData object passing in the form element that we grabbed from the DOM. This bundles up everything with a name attribute from our form giving us the ability to access submitted input data.

After we create our FormData object we grab the values from the inputs using the .get() method (make sure to pass in the name attribute values here from the inputs, not the class name or id). After this step, if this were a real-world application we would most likely be sending the form data off to a server somewhere with a fetch request. For demonstration purposes though, we’ll just keep it simple and render a message to the user letting them know they’ve signed up.

Let’s go ahead and try out our newsletter form now that we have everything set up.

Newsletter form with user input

Now if we click Signup all our form data will be submitted and we should get a pop-up message letting us know we’ve signed up.

Newsletter signup message

Conclusion

FormData objects are a great tool to use with your HTML forms. They allow you to easily access everything from your form without having to individually get and store each element or input value one by one.

Just create a new object from the FormData constructor passing in your form element and utilize the FormData methods that are provided.

Discussion (4)

Collapse
lukeshiru profile image
LUKESHIRU

Indeed, the most useful thing about FormData is that you can use it with fetch, if you only want to get the values of the form elements, you can access them like this:

const {
    email_input: { value: email },
    name_input: { value: name }
} = newsletterForm;
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
birajmainali profile image
Biraj Mainali

Also we can do like this...

 <form id="data--json">
   <input type="text" id="FirstName" value="John" />
   <input type="text" id="LastName" value="Smith" />
 </form>

Enter fullscreen mode Exit fullscreen mode
const jsonForm = () => {
  let data = {};
  const formElem = document.querySelectorAll("#data--json > input");
  for (let i = 0; i < formElem.length; i++) {
    const key = formElem[i].getAttribute("id");
    const elem = formElem[i];
    data[`${key}`] = elem.value;
  }
  return data;
};

console.log(jsonForm());
Enter fullscreen mode Exit fullscreen mode
Collapse
lukeshiru profile image
LUKESHIRU • Edited on

If you really don't want to use FormData or simply get the values from the form, you could still do your logic without the for:

/** @param {HTMLFormElement} form */
const jsonForm = form =>
    Object.fromEntries(
        [...form.querySelectorAll("input")].map(
            /** @param {HTMLInputElement} input */ ({ name, value }) => [
                name,
                value
            ]
        )
    );

console.log(jsonForm(document.querySelector("#data--json")));
Enter fullscreen mode Exit fullscreen mode
Collapse
davidskuza profile image
David Skuza

You can do Object.fromEntries(new FormData(document.querySelector('#data--json')))