【问题标题】:Form Data Returning Null in LocalStorage - LocalStorage Undefined Error?LocalStorage 中的表单数据返回 Null - LocalStorage 未定义错误?
【发布时间】:2021-01-01 21:17:04
【问题描述】:

我正在努力将预订添加到localStorage 中的数组中,我终于开始工作了。它将添加到存储的正确区域,但是它返回值null。我的错误是说 localStorage 没有定义,windowdocument 也没有定义?

我试图基本上初始化一个空数组以添加信息,这是有效的,但它每次都向数组添加 null。我认为我可能在错误的地方得到了一些东西,或者没有定义一些东西,但无法弄清楚问题出在哪里。我之前不需要初始化 localStorage 并且它工作(在一定程度上)?我已经阅读了一些 SO 答案,但大多数都是针对 React 或 Native 的,对我没有用。

谁能帮我理解我哪里出错了?

bookings = []; 

$("#submit").click(function () {

    var bookings = JSON.parse(localStorage.getItem('bookings')) || [];
    var newBooking = document.getElementsByTagName('input').value;

    bookings.push(newBooking)

    var json = JSON.stringify(bookings);
    window.localStorage.setItem("bookings", json);
}); 

HTML 表单

 <form id="regForm" name="regForm" onsubmit="return setAction(this)" class="col-sm-6">

        <div class="row">
            <input type="text" id="fname" placeholder="First Name" name="fname" required>
            <input type="text" id="lname" placeholder="Last Name" name="lname" required>
            <input id="submit" type="submit" value="Submit">
        </div>

    </form>

我想通过输入获取元素,因为将来我的表单中会有更多字段。

bookings = []; 

document.getElementById("submit").addEventListener("click", function () {

    var bookings = JSON.parse(localStorage.getItem('bookings')) || [];
    var newBooking = document.getElementsByTagName('input').value;

    bookings.push(newBooking)

    var json = JSON.stringify(bookings);
    window.localStorage.setItem("bookings", json);
});
<form id="regForm" name="regForm" onsubmit="return false" class="col-sm-6">

        <div class="row">
            <input type="text" id="fname" placeholder="First Name" name="fname" required>
            <input type="text" id="lname" placeholder="Last Name" name="lname" required>
            <input id="submit" type="submit" value="Submit">
        </div>

    </form>

【问题讨论】:

  • 您在哪一行出现错误?确切的错误信息是什么?
  • 基本上从3、5、6、11开始?错误是“$ 未定义”、“localStorage 未定义”、“文档未定义”、“窗口未定义”、“setAction 已定义但从未使用” - 最后一个错误与表单操作有关。
  • 您在getElementsByTagName 的结果上调用.value,这是一个集合,而不是单个输入元素。我建议首先使用querySelectorAll 以避免现场HTMLCollection 的复杂性,但由于您要存储所有结果,因此您应该查看form 上的serialize
  • @pilchard 说得有道理,我不确定检索输入数据的正确方法,我试试看!
  • SerializeArray 工作!我在以前的代码中有过,但它不起作用,现在效果很好!谢谢你的帮助!最后期限是几天后,我开始恐慌了。

标签: javascript jquery arrays local-storage


【解决方案1】:

问题在于获取输入元素,使用serializeArray方法后数据正确存储,感谢cmets中的人。

 var bookings = []; 

 $("#submit").click(function () {

    bookings = JSON.parse(localStorage.getItem('bookings')) || [];
    var newBooking = $("#regForm").serializeArray();
    //var newBooking = document.querySelectorAll('input').value;

    bookings.push(newBooking)

    var json = JSON.stringify(bookings);
    window.localStorage.setItem("bookings", json);
 });

如果其他人需要此解决方案,请发布。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2019-02-27
    • 2018-02-14
    • 2021-03-18
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多