Serializing form data with the vanilla JS FormData() object

Introduction

Let’s say you have a form. When it’s submitted, you want to get the values of all of the fields and submit them to an API.

<form>
    <label for="title">Title</label>
    <input type="text" name="title" id="title" value="Go to Hogwarts">

    <label for="body">Body</label>
    <textarea id="body" name="body">Learn magic, play Quidditch, and drink some butter beer.</textarea>

    <input type="hidden" name="userId" value="1">

    <button>Submit</button>
</form>

How do you easily get the values of all of the fields ?

Today, we’re going to look at an easy, native way to do that: FormData().

Vidéo

Browser compatibility

The FormData() constructor works in all modern browsers, and IE10 and above.

Unfortunately, iterators and the for…of method do not work in IE at all, and cannot be polyfilled.

Next week, we’ll look at some more backwards compatible ways to serialize form data into arrays, objects, and search parameter strings.