FormData: FormData() constructor
The FormData() constructor creates a new FormData object.
Note: This feature is available in Web Workers.
Syntax
new FormData()
new FormData(form)
new FormData(form, submitter)
Parameters
formOptional-
An HTML
<form>element — when specified, theFormDataobject will be populated with theform's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content. submitterOptional-
A submit button that is a member of the
form. If thesubmitterhas anameattribute or is an<input type="image">, its data will be included in theFormDataobject (e.g.btnName=btnValue).
Exceptions
TypeError-
Thrown if the specified
submitteris not a submit button. NotFoundErrorDOMException-
Thrown if the specified
submitterisn't a member of theform. Thesubmittermust be either a descendant of the form element or must have aformattribute referring to the form.
Examples
Creating an empty FormData
Prepopulating from a HTML form element
You can specify the optional form and submitter arguments when creating the FormData object, to prepopulate it with values from the specified form.
Note: Only successful form controls are included in a FormData object, i.e. those with a name and not in a disabled state.
HTML
<form id="form">
<input type="text" name="text1" value="foo" />
<input type="text" name="text2" value="bar" />
<input type="text" name="text2" value="baz" />
<input type="checkbox" name="check" checked disabled />
<button name="intent" value="save">Save</button>
<button name="intent" value="saveAsCopy">Save As Copy</button>
</form>
<output id="output"></output>
JavaScript
const form = document.getElementById("form");
const submitter = document.querySelector("button[value=save]");
const formData = new FormData(form, submitter);
const output = document.getElementById("output");
for (const [key, value] of formData) {
output.textContent += `${key}: ${value}\n`;
}
Result
For brevity, the <form> element is hidden from view.
Specifications
| Specification |
|---|
| XMLHttpRequest Standard # dom-formdata |
Browser compatibility
BCD tables only load in the browser