检索表单值以将其作为JSON字符串发送到localStorage的最简单方法是什么?我启动了一个带有for循环的函数,但是我被卡住了。非常感谢非常赞赏(对此仍然很新)请不要JQuery。谢谢
<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'));
答案 0 :(得分:3)
不需要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(并且它们应该),你也可以在外层使用reduce而不是在表单id上使用map和hash:
let userdata = [...document.forms].reduce((result, frm) => {
result[frm.id] = [...frm.elements].reduce((obj, el) => {
等等。
答案 1 :(得分:3)
你可以这样做:
<强> 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);