Vishera Vishera - 4 months ago 24
HTML Question

How to populate an HTML input field from HTML LocalStorage

I'm using JavaScript and HTML to create a form. I have the form, and I will save it's contents into the 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">
<td>Employee Name: </td>
<td><input type="text" name="empname"></td>
<td id="lsempname"></td>
<td>Customer Name: </td>
<td><input type="text" name="custname"></td>
<tr><td colspan="2"><button id="indnotebutt" onclick=genres();><b>Submit</b><button></td>

the local storage will be updated base on the following JS if:

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:

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.

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

But you need to give your input an ID...

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