如何在表单提交上使用localstorage

时间:2014-09-13 17:30:41

标签: jquery html5 forms submit local-storage

我有下一个表格 -

         <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上, 我需要改变什么?使用什么方法/行动?

1 个答案:

答案 0 :(得分: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操作。我无法在那里确认给你看。