【问题标题】:how to use localstorage on form submit如何在表单提交上使用本地存储
【发布时间】:2014-11-07 15:58:11
【问题描述】:

我有下一个表格 -

         <form name="local_storage_form" method="post" autocomplete="on" data-theme="e" style="padding: 10px;">


         <label for="id">identity card number</label><input type="text" name="id" id="id" placeholder="identity card number..." data-theme="e" required class="localStore">
         <label for="hphone">Home Phone Number</label><input type="tel" name="hphone" id="hphone" placeholder="Home Phone Number..." data-theme="e" class="localStore">
         <label for="mphone">Mobile Phone Number</label><input type="text" name="mphone" id="mphone" placeholder="Mobile Phone Number..." data-theme="e" required class="localStore" oninvalid="setCustomValidity('Invaild Phone Number (05********)')">
         <label for="bdate">Birth Date</label><input type="date" name="bdate" placeholder="Birth Date..." id="bdate" data-theme="e" required class="localStore">
         <label for="email">Email Address</label><input type="email" name="email" id="email" autocomplete="off" placeholder="Email Address..." data-theme="e" required class="localStore">
         <input type="submit" value="Submit">
         </form>

和下一个脚本 -

$('#local_storage_form').submit(function(e) {
    e.preventDefault(); // prevent the form from attempting to send to the web server
    var $inputs = $('#local_storage_form :input');

    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

    localStorage.setItem('testForm', JSON.stringify(values));
});

我在提交时仍然收到 505 错误,并且值没有保存在 localStorage 中, 我需要改变什么?使用什么方法/动作?

【问题讨论】:

  • 表单的名称为 local_storage_form 而不是 id 并且您在 jquery 中使用 id 选择器
  • 还是无法提交,是否需要更改表单方法或提交按钮?

标签: jquery html forms submit local-storage


【解决方案1】:

在表单中添加一个 id 并将您的 jquery 脚本更改为:

$('#local_storage_form').submit(function(e) {
    e.preventDefault(); // prevent the form from attempting to send to the web server
    var $inputs = $('#local_storage_form :input');

    var values = {};
    $inputs.each(function() {
        values[$(this).attr("name")] = $(this).val();
    });

    localStorage.setItem('testForm', JSON.stringify(values));
});

我不知道 jsfiddle.net 是否禁用了 localStorage 操作。我无法在那里确认给你看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 2011-11-24
    • 1970-01-01
    • 2022-01-21
    • 2018-01-04
    • 2011-04-14
    • 2015-12-02
    • 2015-01-05
    相关资源
    最近更新 更多