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,
- setItem() method adds key and value to localStorage
- getItem() method retrieves a value by the key from localStorage
- removeItem() method deletes an item by key from localStorage
- clear(): method deletes all data from localStorage
- 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.
- <!DOCTYPE html>
- <html lang=”en”>
- <head>
- <meta charset=”UTF-8″>
- <title>Title</title>
- <script language=”JavaScript” type=”text/javascript”>
- function RememberCredentials(){
- localStorage.setItem(“Username”, document.getElementById(‘txtUsername’).value);
- localStorage.setItem(“Password”, document.getElementById(‘txtPassword’).value);
- }
-
- function LoadCredentials(){
- document.getElementById(‘txtUsername’).value = localStorage.getItem(“Username”);
- document.getElementById(‘txtPassword’).value = localStorage.getItem(“Password”);
- }
-
- function RemoveCredentials(){
- localStorage.removeItem(“Username”);
- localStorage.removeItem(“Password”);
-
- }
-
- </script>
- </head>
- <body>
- <table style=”width:500px; height: 200px”>
- <tr>
- <td>Username</td>
- <td>
- <input type=”text” id=”txtUsername” />
- </td>
- </tr>
- <tr>
- <td>Password</td>
- <td>
- <input type=”password” id=”txtPassword” />
- </td>
- </tr>
- <tr>
- <td>
- <button onclick=”RememberCredentials()”>Remember Credentials</button>
- </td>
- <td>
- <button onclick=”RemoveCredentials()”>Clear</button>
- </td>
- </tr>
- </table>
- <script language=”JavaScript” type=”text/javascript”>
- LoadCredentials();
- </script>
- </body>
- </html>
Please leave us your comment below and share.