How to use Javascript localStorage to retain values of HTML input elements on Page Refresh?
localStorage in Javascript is used to retain the values of the HTML input elements on the page refresh. setItem() and getItem() methods are used to set and get the data from the localStorage. clear() method is used to clear the data from the localStorage.
Suppose I have following 2 textboxes and buttons in my HTML page.
<input type="text" id="text1" value="" />
<button type="button" id="myButton1" onclick="myButtonClicked('text1')">Click Me</button>
<input type="text" id="text2" value="" />
<button type="button" id="myButton2" onclick="myButtonClicked('text2')">Click Me</button>
I fill some data in each textbox. Now when I refresh the page, the data is lost. I want to retain that data on the page refresh. I will use localStorage for this purpose.
//Store values on button click
function myButtonClicked(id)
{
var aLocalStorage = [];
if(localStorage.getItem('myLocalStorage') != null)
{
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));
//get stored item from localStorage by json parsing
}
aLocalStorage.push(id);
aLocalStorage.push(document.getElementById(id).value);
localStorage.setItem('myLocalStorage', JSON.stringify(aLocalStorage));
//stored the entered element id and value in localStorage by doing stringify
}
Now when the page is refresh, call the following function on $(Idocument).ready event like this
$(document).ready(function()
{
retainValues();
});
function retainValues()
{
if(localStorage.getItem('myLocalStorage') != null)
{
var aLocalStorage =[];
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));
var i = 0;
while (i < aLocalStorage.length)
{
if (document.getElementById(aLocalStorage[i]) != null)
{
document.getElementById(aLocalStorage[i]).value = shoppingCartList[i+1];
}
i = i + 2;
}
}
}