Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello. I am using the following code to get and set data to the LocalStorage on the user's device:

HTML
localStorage.setItem("name", "Hello World!");
document.write(localStorage.getItem("name")); //Hello World!


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:

HTML
<form>
    <label>Company Name:</label>
    <input name="companyname" placeholder="Type Here" type="text">
</form>


Thanks in advance!
Posted

I found a solution that works.

I gave the textbox an ID of "companyname", and I changed the setting saving code to:

JavaScript
var companyNameInput = document.getElementById("companyname");
localStorage["companyName"] = companyNameInput.value;


And here's what I used to load the setting:

JavaScript
var companyNameInput = document.getElementById("companyname");
var companyNameSetting = localStorage["companyName"];

// Load the Company Name.
if (companyNameSetting == null) {
    companyNameInput.value = "";
}
else {
    companyNameInput.value = companyNameSetting;
}
 
Share this answer
 
Hope you will find this useful.
JavaScript
<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>


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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900