admin管理员组

文章数量:1134248

I have a FormData object which I create in javascript from an HTML form like so. The FormData object doesn't seem very well documented (it may just be me searching the wrong things!).

var form = new FormData(document.getElementById("form"));

My Question

How do I access the different input values of this FormData object before I send it off? Eg. form.name accesses the value that was entered into the input with the name form.name.

I have a FormData object which I create in javascript from an HTML form like so. The FormData object doesn't seem very well documented (it may just be me searching the wrong things!).

var form = new FormData(document.getElementById("form"));

My Question

How do I access the different input values of this FormData object before I send it off? Eg. form.name accesses the value that was entered into the input with the name form.name.

Share Improve this question asked Sep 4, 2013 at 5:50 StuStirlingStuStirling 16.2k23 gold badges96 silver badges155 bronze badges 1
  • 1 If by 'access' you meant visually inspect, try console.info(...myFormData);, which apparently casted the object to an array, at least in FF. – DWB Commented Apr 17, 2023 at 21:18
Add a comment  | 

15 Answers 15

Reset to default 36

First thing I don't think it's possible to build a FormData object from a form as you've specified, and to get values from the form use the method described in the accepted answer -- this is more of an addendum!

It looks like you can get some data out of a FormData object:

var formData = new FormData();
formData.append("email", "[email protected]");
formData.append("email", "[email protected]");
formData.get("email");

this will only return the first item for that key, in this case it will return '[email protected]', to get all the email addresses use the below code

formData.getAll("email")

Please see also: MDN article on formdata get method.

FormData.get will do what you want and works in all browsers since around 2018-2019. Given this form:

<form id="form">
  <input name="inputTypeName">
</form>

You can access the value of that input via

var form = new FormData(document.getElementById("form"));
var inputValue = form.get("inputTypeName");

It seems you can't get values of the form element using FormData.

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

However you can achieve it using simple Javascript like this

var formElements = document.forms['myform'].elements['inputTypeName'].value;

According to MDN:

An object implementing FormData can directly be used in a for...of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries())

Therefore you can access FormData values like that:

var formData = new FormData(myForm);

for (var p of formData) {
    let name = p[0];
    let value = p[1];

    console.log(name, value)
}

This is a solution to retrieve the key-value pairs from the FormData:

var data = new FormData( document.getElementById('form') );
data = data.entries();              
var obj = data.next();
var retrieved = {};             
while(undefined !== obj.value) {    
    retrieved[obj.value[0]] = obj.value[1];
    obj = data.next();
}
console.log('retrieved: ',retrieved);

Just to add to the previous solution from @Jeff Daze - you can use the FormData.getAll("key name") function to retrieve all of the data from the object.

My solution with for-of

const formData = new FormData(document.getElementById('form'))

for (const [key, value] of formData) {
  console.log('»', key, value)
}

I came across an extremely simple way to convert form data into an object:

  const formData = new FormData(evt.currentTarget)
  const formObject = Object.fromEntries(formData.entries()) // {}

Note that for multiple entries (for ex. checkbox); you need to handle separately with formData.getAll("favFruits") (for example)

const handleSubmit = (evt) => {
  evt.preventDefault()
  const formData = new FormData(evt.currentTarget)
  const formObject = Object.fromEntries(formData.entries())

  // caveat for multiple values
  formObject.favFruits = formData.getAll("favFruits")
  console.log(formObject)
}
<form onsubmit="handleSubmit(event)">
  <input type="text" value="James" name="firstName" required placeholder="First Name..." />
  <input type="text" name="lastName" value="Bond" required placeholder="Last Name..." />
  <label>
  <br />
  <h5>Fav Fruits</h5>
  <input type="checkbox" name="favFruits" value="watermelon" />
  Watermelon
  </label>
  <label>
  <input type="checkbox" name="favFruits" checked value="apple" />
  Apple
  </label>
  <label>
  <input type="checkbox" name="favFruits" checked value="orange" />
  Orange
  </label>
  <br />
  <br />
  <input type="submit" value="Submit" />
</form>

it will work

   // let form = document.querySelector("form");
  
const form = new FormData();
  
form.append("username", "Groucho");
form.append("accountnum", 123456); 
let data = new FormData(form)
formObj = {};
for (var pair of data.entries()) {
  formObj[pair[0]] = pair[1]
}
console.log(formObj)

If what you're trying to do is get the content of the FormData or append to it, this is what you should use:

Let's say you want to upload an image like so:

<input type="file" name="image data" onChange={e => 
uploadPic(e)} />

On change handler function:

const handleChange = e => {
    // Create a test FormData object since that's what is needed to save image in server

   let formData = new FormData();

    //adds data to the form object

    formData.append('imageName', new Date.now());
    formData.append('imageData', e.target.files[0]);

}

append: adds an entry to the creates formData object where imageData is the key and e.target.files[0] is the property

You can now send this imageData object which contains data of the image to your server for processing

but to confirm if this formData has values a simple console.log(formData)/won't do it, what you should do is this:

//don't forget to add this code to your on change handler 
function
for (var value of formData.values()) {
   console.log(value); 
}

//I hope that explains my answer, it works for vanilla JavaScript and React.js...thanks in advance for your upvote

A simple HTML5 way (form to object) using the runarberg/formsquare library (npm i --save formsquare):

import formsquare from "formsquare";

const valuesObject = formsquare.filter((el) => !el.disabled).parse(document.getElementById('myForm'));
//=> {"foo": "bar"}

https://github.com/runarberg/formsquare

Creating a FormData object in JavaScript is quite straightforward and it's a useful tool for working with HTML forms. Here's how you can create a FormData object from an HTML form:

Assuming you have an HTML form with the id "myForm"

const formElement = document.getElementById('myForm');
const formData = new FormData(formElement);

The FormData constructor takes a reference to your HTML form element as an argument, and it automatically collects all the form fields and their values.

Once you have the formData object, you can access and manipulate the form data easily. For example, you can append additional data to it or send it via an AJAX request.

While the FormData object itself may not be as well-documented as other JavaScript features, it's part of the HTML Living Standard,

Quite similar to @Aakash's answer, but this one-liner will also log all array entries:

Object.fromEntries([...formData.keys()].map(key => [key, formData.getAll(key)]))

const onSubmit = (e) => {
  e.preventDefault();
  const formData = new FormData(e.currentTarget);
  console.log(Object.fromEntries([...formData.keys()].map(key => [key, formData.getAll(key)])));
}
<form onsubmit="onSubmit(event)">
  <input type="text" name="age" value="23" />
  <input type="text" name="hobby[]" value="foo" />
  <input type="text" name="hobby[]" value="bar" />
  <input type="submit" value="Submit" />
</form>

Another solution:
HTML:

<form>
<input name="searchtext"  type="search" >'
<input name="searchbtn" type="submit" value="" class="sb" >
</form>

JS:

$('.sb').click( function() {
    var myvar=document.querySelector('[name="searchtext"]').value;
    console.log("Variable value: " + myvar);
});

Try this:

<html>
<body>
    <form id="form">
        <input type="text" value="Jane Doe" name="name" placeholder="Name" /><br>
        <input type="number" name="age" value="18" placeholder="Age" /><br>
        <input type="number" name="contact" placeholder="Contact" disabled /><br>
    </form>
    <script>
        console.log('Name : ', (formVals = document.getElementById('form')).name.value );
        // more efficient
        console.log('Age : ', formVals.age.value);
        console.log('Contact : ', formVals.contact.value);

        console.log('Name by FormData : ', (formData = new FormData(formVals)).get('name'));
        // less efficient
        console.log('Age by FormData : ', formData.get('age'));
        console.log('Contact by FormData : ', formData.get('contact'));
    </script>
</body>
</html>

本文标签: javascriptAccessing FormData ValuesStack Overflow