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. 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 { } 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") Complete example <html> <style> <fieldset> </fieldset> <fieldset> </div> <script> const keyinp=document.getElementById("key"); btninp.onclick=function(){ const key=keyinp.value; console.log(key); localStorage.setItem(key,value); } } for(let k=0;k<localStorage.length;k++) } Conclusion: In this example we learned how to store data in local storage in javscript, and retrieve and delete data from local storage object.
Javascript Local Storage
Insert Data
Insert Data
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+":"+value+"
";
<head>
<title>Javascript Local Storage</title>
input{
padding:8px;
height:40px;
}
fieldset{
margin-bottom:30px;}
</style>
</head>
<body>
<h2>Javascript Local Storage</h2>
<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>
<legend>Fetach Local Storage Data:</legend>
<div id="output">
</fieldset>
</body>
const valueinp=document.getElementById("value");
const btninp=document.getElementById("btn");
const outputinp=document.getElementById("output");
const value=valueinp.value;
if(key&&value)
{
location.reload();
{
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+" : "+value+"<br /><br />";
</script>
</html>
Article Contributed By :
|
|
|
|
4160 Views |