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.
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.
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.
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.
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.