【问题标题】:How to send HTML form values to localstorage in JSON string using JavaScript如何使用 JavaScript 以 JSON 字符串将 HTML 表单值发送到本地存储
【发布时间】:2018-08-18 11:26:44
【问题描述】:

检索表单值以作为 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'));

【问题讨论】:

    标签: javascript json local-storage


    【解决方案1】:

    你可以这样做:

    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);
    

    【讨论】:

    • 这和我的回答不一样...怎么样?
    • @JaredSmith 我不知道你为什么在这里有这种态度,但是好的,我很高兴让你知道它有什么不同。首先,我是在您提交答案之前开始写的,所以在提交我的答案之前我没有看到您的答案。现在就其不同之处而言,1. 它只针对一个表单(而您的针对页面上的每个表单)2. 它只存储输入数据(而你的也存储按钮)3.我认为它更具可读性
    【解决方案2】:

    不需要 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) => {
    

    等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-12
      • 2014-10-21
      • 2021-08-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-29
      相关资源
      最近更新 更多