Javascript How to store data in local storage?

Last updated May 08, 2021

In this Javascript Local storage example we will cover how to store and retrieve data from local storage. What is local storage? Local storage properties allows user to store data in key value pairs in the web browser. This local storage object stores the data without expiration date. This local storage data will not be deleted when we close the window. This local storage will be a read only property.

Let's check simple Javascript local storage example

Create simple html file which contains a input fields to enter key and values and one button to save the data.

 

 

 

Javascript Local Storage

 


Insert Data



Insert Data

 

 

 

How to store data in Local Storage?

To store data on Local Storage browser we need to use localStorage object. To store the each data item we need to pass key and value to the setItem() method.

localStorage.setItem(key,value)

 

 

How to fetch data from Local Storage?

To fetch the data from the local storage first we need to fetch all keys first then fetch the values by passing the key to localStorage.getItem(key) method.

 

for(let k=0;k {
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+":"+value+"
";

}

 

 

How to delete data from Local Storage?

To delete the specific key item data from the local storage we will use localStorage.removeItem(key) method by passing the key name.

 

localStorage.removeItem("key Name")

 

Javascript Local Storage

 

 

Complete example

<html>
<head>
<title>Javascript Local Storage</title>

<style>
input{
padding:8px;
height:40px;
}
fieldset{
margin-bottom:30px;}
</style>
</head>
<body>
<h2>Javascript Local Storage</h2>

<fieldset>
<legend>Insert Data</legend>
<input type="text" id="key" placeholder="Enter Key..."/>
<input type="text" id="value" placeholder="Enter Value..."/>
<button type="button" id="btn">Insert Data</button>

</fieldset>

<fieldset>
<legend>Fetach Local Storage Data:</legend>
<div id="output">

</div>
</fieldset>
</body>

<script>

const keyinp=document.getElementById("key");
const valueinp=document.getElementById("value");
const btninp=document.getElementById("btn");
const outputinp=document.getElementById("output");

btninp.onclick=function(){

const key=keyinp.value;
const value=valueinp.value;

console.log(key);
if(key&&value)
{

    localStorage.setItem(key,value);
    location.reload();
    

}

}

for(let k=0;k<localStorage.length;k++)
{
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+" : "+value+"<br /><br />";

}
</script>
</html>

 

Conclusion: In this example we learned how to store data in local storage in javscript, and retrieve and delete data from local storage object.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

4543 Views