将HTML表单数据保存到本地存储

马蒂

我有一个表单部分,人们可以在其中添加他们的电子邮件地址。

我有几个问题:

(1)提交电子邮件地址后页面刷新(我知道如果没有ajax或异步解决方案,这是不可避免的)。这会导致第二个问题,

(2)我似乎无法将这些电子邮件另存为数组并使用 JSON.parse(localStorage.getItem('EmailsStuff'))

我的JS / Jquery的一部分

var total = [];
                $(document).on("click", ":submit", function(e) {
                    var stuff = ($($email).val())
                    total = [JSON.stringify(stuff)];

                    localStorage.setItem('EmailsStuff', JSON.stringify(total));
            });

和html:

<form class="newsletter">

        <input type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />
        <input type="submit" value="Thanks!" class="newsletter-email" id="fast"/>
    </form>

如果我采样它会起作用:

localStorage.setItem('sample',JSON.stringify(["bob", "susan", "rafiki"]);

并因此将其读取为

JSON.parse(localStorage.getItem('sample'));
卡鲁姆

您的电子邮件输入选择器似乎错误,请尝试将其更改为:

var stuff = $('#email').val();

并给您输入一个ID:

<input id="email" type="email" value="" placeholder="Join Update List Here" class ="newsletter-email" />

看到这个小提琴:https : //jsfiddle.net/m8w1uaso/

编辑:如果要保留所有先前输入的电子邮件地址,并在每次提交表单时将其添加到此数组,则可以执行以下操作:

$(document).on("click", ":submit", function(e) {
  var stuff = ($('#email').val());
    // Load emails
  var emails = JSON.parse(localStorage.getItem('EmailsStuff'));
  if (emails) {
    // If the item exists in local storage push the new email address to the array and and save
    emails.push(stuff);
    localStorage.setItem('EmailsStuff', JSON.stringify(emails));
  } else {
    // If the item doesn't exist in local storage set the item to a new array containing new email address
    localStorage.setItem('EmailsStuff', JSON.stringify([stuff]));
  }
});

$(document).on("click", "#loadEmail", function(e) {
  alert(JSON.parse(localStorage.getItem('EmailsStuff')));
});

看到这个小提琴:https : //jsfiddle.net/v9c6xnmh/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章