what is the easiest way to retrieve form values to send to localStorage as a JSON string? I started a function with a for loop but am stuck..any nudges are greatly appreciated(still very new to this) No JQuery please. Thank you
<input type="submit" name="submit" value="submitOrder" onclick="return getValues();">
var userOrder='';
function getValues(){
for(var i=0; i < document.forms[0].length - 1; i++){
console.log(document.forms[0][i]);
return false;
}
}
localStorage.setItem('userOrder',JSON.stringify(userOrder));
console.log(localStorage.getItem('userOrder'));
No need for jQuery. This uses ES 2015 syntax but if you need to support old browsers just run it through babel.
// Iterate over all the forms in the document as an array,
// the [...stuff] turns the nodelist into a real array
let userdata = [...document.forms].map(form => {
// iterate over all the relevant elements in the form and
// create key/value pairs for the name/object
return [...form.elements].reduce((obj, el) => {
// Every form control should have a name attribute
obj[el.name] = el.value;
return obj;
}, {});
});
// convert the data object to a JSON string and store it
localStorage.setItem('userOrder', JSON.stringify(userdata));
// pull it pack out and parse it back into an object
let data = JSON.parse(localStorage.getItem('userOrder'));
If the forms all have ids (and they should) you could also use reduce in the outer layer instead of map and hash on the form id:
let userdata = [...document.forms].reduce((result, frm) => {
result[frm.id] = [...frm.elements].reduce((obj, el) => {
and so on.
You could do it like this:
html:
<form id="myform">
<input type="text" name="test">
<input type="submit" value="submitOrder">
</form>
js:
const userOrder = {};
function getValues(e) {
// turn form elements object into an array
const elements = Array.prototype.slice.call(e.target.elements);
// go over the array storing input name & value pairs
elements.forEach((el) => {
if (el.type !== "submit") {
userOrder[el.name] = el.value;
}
});
// finally save to localStorage
localStorage.setItem('userOrder', JSON.stringify(userOrder));
}
document.getElementById("myform").addEventListener("submit", getValues);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.