[英]How do I save HTML form field values to localStorage using JavaScript?
[英]How to send HTML form values to localstorage in JSON string using JavaScript
检索表单值以JSON字符串形式发送到localStorage的最简单方法是什么? 我用for循环开始了一个函数,但是被卡住了。 谢谢
<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'));
不需要jQuery。 它使用ES 2015语法,但是如果您需要支持旧版浏览器,则可以通过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'));
如果所有表单都具有ID(并且应该具有ID),那么您也可以在外层使用reduce来代替表单ID上的map和hash:
let userdata = [...document.forms].reduce((result, frm) => {
result[frm.id] = [...frm.elements].reduce((obj, el) => {
等等。
您可以这样做:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.