如何记住尚未提交的表单数据?

时间:2017-01-06 11:37:02

标签: javascript jquery html forms

如何让浏览器记住用户在表单中输入的内容(尚未提交)并使页面刷新不影响输入的数据?

我有一个用户输入号码的表格。最初,表单默认为0。我将数据存储在localStorage中,因此浏览器可以记住数据。但是,刷新页面时,用户输入的数据将消失,默认情况下显示0。 (仍然存在localStorage数据)

我尝试使用jQuery的

$(".formClassName").val(localStorage.getItem(key)); 

但它不起作用。有人可以给我一些建议吗?提前谢谢你。

已编辑:我的表单如下:

<form>
  <!--There are multiple forms, and the only difference among them is the "name" attribute -->
  Enter a number <input type="text" value="0" class"dataEntered" name="****">
  <!--The button below saves the data entered in the above form -->
  <input type="button" class="savedata" value="Save Value" name="****">
</form>

我正在将数据添加到localStorage,如下所示:

//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
    //retrieve the number entered in the form
    var userNum = $(this).siblings(".dataEntered").val();
    //retrieve the value in name attribute
    var thisFormName = $(this).attr("name");
    //store the data
    localStorage.setItem(thisFormName, userNum);

    //Now that the save button has been pressed (not submitted to the 
    //server yet), and the data is stored in localStorage, I want to
    //the page to show the number in userNum even after you refresh the page
    //but this does not work.
    $(".dataEntered").val(localStorage.setItem(thisFormName));

});
</script>

2 个答案:

答案 0 :(得分:1)

结帐codepen我知道它显示了问题的功能性解决方案。此外,您需要确保jQuery脚本检查DOM是否准备就绪,您可以使用$(function() { }) .ready()的简写来做到这一点。

$(function() {
  var input = $("[type=text]");
  var thisFormName = input.attr("name");

  if (localStorage.getItem(thisFormName)) {
    var value = parseInt(localStorage.getItem(thisFormName));
    input.val(value);
  } 

  $(document).on("click", ".savedata", function(e) {
    var userNum = input.val();
    localStorage.setItem(thisFormName, userNum);
    input.val(localStorage.getItem(thisFormName));
  });
});

答案 1 :(得分:1)

使用cookie:

function addCookie(sName,sValue,day) {
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate()+day);
    document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString(); 
}
function getCookies() {
    var showAllCookie = '';
    if(!document.cookie == ''){
    var arrCookie = document.cookie.split('; ');
    var arrLength = arrCookie.length;
    var targetcookie ={};
   for(var i=0; i<arrLength; i++) {
        targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
        }
    return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type); 

除非删除cookie,否则可以记住cookiesample.type。