简体   繁体   English

如何从HTML LocalStorage填充HTML输入字段

[英]How to populate an HTML input field from HTML LocalStorage

I'm using JavaScript and HTML to create a form. 我正在使用JavaScript和HTML创建表单。 I have the form, and I will save it's contents into the LocalStorage. 我有了表单,并将其内容保存到LocalStorage中。 One of these fields I want to be populated once, and then display the value from local storage. 我想一次填充这些字段之一,然后显示本地存储中的值。 If the field gets edited, the localstorage to be updated. 如果该字段被编辑,则将更新本地存储。

I managed to do everything, but display the local storage value in the form input field.: 我设法完成了所有工作,但是在表单输入字段中显示了本地存储值。

<form name="myForm" action="newcuaneeded.html" onsubmit="return genres();"method=post>
<table border="0">
    <tr>
        <td>Employee Name: </td>
        <td><input type="text" name="empname"></td>
        <td id="lsempname"></td>
    </tr>
    <tr>
        <td>Customer Name: </td>
        <td><input type="text" name="custname"></td>
    </tr>
    <tr><td colspan="2"><button id="indnotebutt" onclick=genres();><b>Submit</b><button></td>
    </tr>
</table>
</form><hr>

the local storage will be updated base on the following JS if: 如果满足以下条件,则将基于以下JS更新本地存储:

if (ename == "") ename = localStorage.getItem("ls-ename");
if (ename != "") localStorage.setItem("ls-ename", ename);

The content of the LocalStorge is displayed next to the field itself with the following JS command: 使用以下JS命令,LocalStorge的内容显示在字段本身旁边:

document.getElementById("lsempname").innerHTML = localStorage.getItem("ls-ename");

Instead of being displayed next to the field, I want it to be in the field itself. 我希望它不会显示在字段旁边,而是希望它位于字段本身中。

For inputs you use the value attribute. 对于输入,您使用value属性。

document.getElementById("empname").value = localStorage.getItem("ls-ename");

But you need to give your input an ID... 但是您需要给您的输入一个ID ...

<input type="text" name="empname" id="empname">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM