I have a FormData object which I create in javascript
from an HTML
form like so. The FormData
object doesn\'t seem very well documente
My solution with for-of
const formData = new FormData(document.getElementById('form'))
for (const [key, value] of formData) {
console.log('»', key, value)
}
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
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.
it will work
let form = document.querySelector("form");
let data = new FormData(form)
formObj = {};
for (var pair of data.entries()) {
formObj[pair[0]] = pair[1]
}
console.log(formObj)
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", "test1@test.com");
formData.append("email", "test2@test.com");
formData.get("email");
this will only return the first item for that key, in this case it will return 'test1@test.com', to get all the email addresses use the below code
formData.getAll("email")
Please see also: MDN article on formdata get method.
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);
});