Getting Form Data With the FormData API
FormData collects a form’s named controls so you can inspect or send their values. It saves you from reading each field separately:
const name =
document.querySelector(
"#name"
).value;
const email =
document.querySelector(
"#email"
).value;
With FormData, the same job starts with the form element:
FormData
View code
<form><label>Name <input name="name" value="Alex"></label>
<fieldset><legend>Topics</legend><label><input name="topic" value="HTML" type="checkbox" checked> HTML</label><label><input name="topic" value="CSS" type="checkbox" checked> CSS</label></fieldset>
<label>Disabled field <input name="disabled" value="Not collected" disabled></label>
<label>Field without a name <input value="Not collected either"></label>
<button id="inspect" type="button">Inspect FormData</button></form>
<pre id="result" tabindex="0" aria-label="Collected form entries"></pre>
<p class="note">Each entry is shown separately, including repeated topic names. Nothing is sent.</p>button, select { padding: .35rem .6rem; border: 1px solid var(--clg); background: var(--cw); color: var(--cb); }
input[type="range"] { width: min(100%, 18rem); vertical-align: middle; }
h2, h3 { font-size: 1rem; }
.note { color: var(--clg); }
form > label { display: block; margin-bottom: .5rem; }
input:not([type="checkbox"]) { max-width: 100%; padding: .25rem; }
fieldset { margin-block: .75rem; border: 1px solid var(--clg); }
button { margin-top: .5rem; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; background: var(--cg); padding: .75rem; }const form = document.querySelector('form');
function inspect() {
document.querySelector('#result').textContent = [...new FormData(form).entries()].map(([name, value]) => `${name}: ${JSON.stringify(value)}`).join('\n');
}
document.querySelector('#inspect').addEventListener('click', inspect);
inspect();Collect and inspect the form values
<form id="contact">
<label for="name">
Name
</label>
<input
id="name"
name="name">
<label for="email">
Email
</label>
<input
id="email"
name="email"
type="email">
<button>
Send
</button>
</form>
The important detail is:
name="..."
FormData works with successful named form controls.
const form =
document.querySelector(
"#contact"
);
const data =
new FormData(form);
Now data contains the form values.
data.get("email");
If the field contains:
hello@example.com
that is what you get.
for (
const [name, value]
of data
) {
console.log(
name,
value
);
}
That is useful while debugging.
Convert to an object
For simple forms:
const object =
Object.fromEntries(data);
Now you may get:
{
name: "Ronalds",
email: "hello@example.com"
}
Be careful with fields that can have several values, such as groups of checkboxes. Object.fromEntries() keeps only one value for repeated names. For those, use:
data.getAll("interest");
Checkboxes
<label>
<input
type="checkbox"
name="interest"
value="css">
CSS
</label>
<label>
<input
type="checkbox"
name="interest"
value="html">
HTML
</label>
Then:
data.getAll("interest");
might return:
["css", "html"]
Send it with fetch()
FormData can be sent directly:
fetch(
form.action,
{
method: form.method,
body: data
}
);
Do not manually set a multipart Content-Type header in this case. The browser creates the correct boundary for the FormData body.
File uploads
This is one place FormData is especially useful.
<input
type="file"
name="photo">
The selected File object can be included automatically.
const data =
new FormData(form);
No manual file serialization is needed.
Use the submit event
A progressive enhancement pattern:
form.addEventListener(
"submit",
async event => {
event.preventDefault();
const data =
new FormData(form);
await fetch(
form.action,
{
method: form.method,
body: data
}
);
}
);
If JavaScript does not run, the form can still submit normally through its action and method.
Respect the submitter
If the form has more than one submit button, the button that triggered the submission may matter. Modern FormData can include a submitter when created with the form and submit button in supporting browsers. Another option is using:
event.submitter
inside the submit handler. That helps when buttons represent different actions such as:
Save draft
Publish
Delete
Disabled controls are not included
A disabled field:
<input
name="email"
disabled>
is not normally submitted. That behaviour also affects FormData. If you need the value to be included but not editable, readonly may be the correct choice for input types that support it.
No name, no data
This field:
<input id="email">
has no name. It will not appear as:
email
in normal form submission or FormData. Add:
name="email"
if it belongs in the submitted data.
Keep the field definitions in HTML
With FormData, JavaScript can use the field definitions already in the form. The HTML already says:
these are the fields
these are their names
these are their values
JavaScript can use that structure directly. For a normal form, that is cleaner than querying every field manually and building another object from scratch.