Use Local Storage In JavaScript

Introduction

 
Local data storage is used to store data permanently on a local drive. JavaScript localStorage object and its methods are used to implement local storage in JavaScript. The data is stored in a key/value pair. The localStorage object has the following methods,
  1. setItem() method adds key and value to localStorage
  2. getItem() method retrieves a value by the key from localStorage
  3. removeItem() method deletes an item by key from localStorage
  4. clear(): method deletes all data from localStorage
  5. key() method gets the key with its index.
The following code snippet reads data from a Web page text box controls and saves them and retrieves them from local storage. Code also removes items and uses other methods. 
  1. <!DOCTYPE html>  
  2. <html lang=”en”>  
  3.     <head>  
  4.         <meta charset=”UTF-8″>  
  5.             <title>Title</title>  
  6.             <script language=”JavaScript” type=”text/javascript”>    
  7. function RememberCredentials(){    
  8.    localStorage.setItem(“Username”, document.getElementById(‘txtUsername’).value);    
  9.    localStorage.setItem(“Password”, document.getElementById(‘txtPassword’).value);    
  10. }    
  11.     
  12. function LoadCredentials(){    
  13.    document.getElementById(‘txtUsername’).value = localStorage.getItem(“Username”);    
  14.    document.getElementById(‘txtPassword’).value = localStorage.getItem(“Password”);    
  15. }    
  16.     
  17. function RemoveCredentials(){    
  18.    localStorage.removeItem(“Username”);    
  19.    localStorage.removeItem(“Password”);    
  20.    //localStorage.clear();    
  21. }    
  22.     
  23. </script>  
  24.         </head>  
  25.         <body>  
  26.             <table style=”width:500px; height: 200px”>  
  27.                 <tr>  
  28.                     <td>Username</td>  
  29.                     <td>  
  30.                         <input type=”text” id=”txtUsername” />  
  31.                     </td>  
  32.                 </tr>  
  33.                 <tr>  
  34.                     <td>Password</td>  
  35.                     <td>  
  36.                         <input type=”password” id=”txtPassword” />  
  37.                     </td>  
  38.                 </tr>  
  39.                 <tr>  
  40.                     <td>  
  41.                         <button onclick=”RememberCredentials()”>Remember Credentials</button>  
  42.                     </td>  
  43.                     <td>  
  44.                         <button onclick=”RemoveCredentials()”>Clear</button>  
  45.                     </td>  
  46.                 </tr>  
  47.             </table>  
  48.             <script language=”JavaScript” type=”text/javascript”>    
  49. LoadCredentials();    
  50. </script>  
  51.         </body>  
  52. </html>   
Please leave us your comment below and share.