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

标签 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>

最佳答案

使用 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); 

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

关于javascript - 如何记住未提交的表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504878/

相关文章:

javascript - 是否可以在不使用断点的情况下使用 Firebug 停止 javascript?

javascript - JS 中的变量重新分配问题,让我无法理解

javascript - JQueryUI 可拖动和可调整大小的框问题

javascript - javascript中的smarty变量

javascript - JavaScript 中的冲突事件

javascript - 从文本框中检索值

html - telegram 如何显示某些网站的图标?

javascript - 单击第一个 <td> 时展开表格行以显示更多内容

javascript - HTML 图像的相对路径。在 Github 页面上找不到 404

javascript - 百分比格式的国际化