Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 4, 2021 11:32 pm GMT

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 forms fields and values.

Using FormData in JavaScript

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

Newsletter form

Lets check out what the HTML looks like for this newsletter form.

One thing to notice here is that weve 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 lets head over to our javascript file and code everything out.

Here you can see how were 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, well just keep it simple and render a message to the user letting them know theyve signed up.

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


Original Link: https://dev.to/coderjay06/how-to-use-the-formdata-object-3ooe

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To