将LocalStorage检索到TextBox [英] Retrieving LocalStorage to TextBox
问题描述
你好.我正在使用以下代码来获取数据并将其设置到用户设备上的LocalStorage:
Hello. I am using the following code to get and set data to the LocalStorage on the user''s device:
localStorage.setItem("name", "Hello World!");
document.write(localStorage.getItem("name")); //Hello World!
这只是保存LocalStorage数据,然后将其显示在网页上作为测试.现在,如何从文本框获取数据并将其设置到文本框?
这是我用于文本框的代码:
This simply saves the LocalStorage data and then displays it on the web page as a test. Now, how can I get and set that data from/to a textbox?
Here''s the code I''m using for my textbox:
<form>
<label>Company Name:</label>
<input name="companyname" placeholder="Type Here" type="text">
</form>
在此先感谢!
Thanks in advance!
推荐答案
我找到了一个可行的解决方案.
我为文本框指定了"companyname"的ID,并将设置保存代码更改为:
I found a solution that works.
I gave the textbox an ID of "companyname", and I changed the setting saving code to:
var companyNameInput = document.getElementById("companyname");
localStorage["companyName"] = companyNameInput.value;
这是我用来加载设置的内容:
And here''s what I used to load the setting:
var companyNameInput = document.getElementById("companyname");
var companyNameSetting = localStorage["companyName"];
// Load the Company Name.
if (companyNameSetting == null) {
companyNameInput.value = "";
}
else {
companyNameInput.value = companyNameSetting;
}
希望您会发现这很有用.
Hope you will find this useful.
<script language="JavaScript">
function loadFromLocalStorage() {
var frmObjects = document.forms[0].elements;
for(obj in frmObjects) {
if(obj.type = 'textbox' && obj.name != null && localStorage.getItem(obj.name) != null) {
obj.value = localStorage.getItem(obj.name);
}
}
}
</script>
<form>
<label>Company Name:</label>
<input name="companyname" placeholder="Type Here" type="text" önblur="localStorage.setItem(this.name, this.value)">
</input></form>
我刚刚提供了有关如何实现要求的概念.您可能需要根据需要修改此代码段.
谢谢&问候,
尼拉·索尼(Nial Soni)
I have just provided a concept on how you can achieve your requirements. You might need to modify this code snippet as per your need.
Thanks & Regards,
Niral Soni
这篇关于将LocalStorage检索到TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!