gpt4 book ai didi

javascript - 使用本地存储中保存的数据填充 HTML 表单

转载 作者:行者123 更新时间:2023-11-27 22:44:54 24 4
gpt4 key购买 nike

我的应用程序将填写的表单数据(带有 ID 和值的输入字段)保存到本地存储,甚至成功加载回来,再次分离解析的 ID 和值。

问题是,一旦页面重新加载,我无法根据已保存到本地存储的数据来预填写表单备份。保存的数据保留在浏览器的资源中,并且控制台记录每个输入字段的正确值。但是,页面本身没有显示任何内容。

这是我的 HTML 结构的示例:

<form id="myForm" method="post">
<input type="submit" onclick="dataSave();" value="Save">
<input class="formField" type="checkbox">Task done!
<input class="formField" type="text">How it went?
</form>

这是当前执行保存和加载到本地存储的 JavaScript:

if (typeof(Storage) !== "undefined"){

// Loading data
function dataLoad(){
var inputParse = JSON.parse(localStorage.getItem('fieldString'));
var inputId;
var inputValue;
var inputType;

$.each(inputParse, function(key, value){
inputId = key;
inputValue = value;

if (inputValue === "true" || inputValue === "false"){
inputType = inputValue;
}
});


$(".formField").each(function(){
inputId = this.id;
document.getElementById(inputId);

if (inputType === "true"){
$(inputId).attr("checked", "checked");
} else {
$(inputId).val(inputValue);
}
});
}

// Saving data
function dataSave(){
var mngrFields = {};

$(".mngr-field").each(function(){
if (this.type == "radio" || this.type == "checkbox"){
mngrFields[this.id] = this.checked;
} else {
mngrFields[this.id] = this.value;
}
});
localStorage.setItem('fieldString', JSON.stringify(mngrFields));
}

为了在页面加载后运行 dataLoad(),我的 $(document).ready( 中有一个简单的 dataLoad();函数(){});

如何使用保存的数据填充表单?我尝试了一些 document.GetElementById 解决方法,但没有成功。

最佳答案

任务很简单:

  • 获取 localStorage 内容(但首先检查它是否存在);
  • 对于每个存储的 ID,检查 DOM 中的 HTML 类型(因为您无法从当前的 localStorage 对象中获知它);
  • 为其分配值或选中属性(如果是单选/复选框);

所以这里是:

function dataLoad() {
if (localStorage.getItem('fieldString') !== null) {
var inputParse = JSON.parse(localStorage.getItem('fieldString'));
$.each(inputParse, function (key, value) {
var field = document.getElementById(key);
if(field.type == 'radio' || field.type == 'checkbox'){
field.checked = value;
}else{
field.value = value;
}
});
}
}

您可以在文档加载时自动调用该函数或将其分配给某个按钮(例如保存操作) - 这取决于您。

祝你好运!

关于javascript - 使用本地存储中保存的数据填充 HTML 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38473924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com