HTML5 client-side storage tutorial: Beyond cookies

1 2 3 4 5 6 Page 6
Page 6 of 6

Listing 4: Storing form changes in localStorage

<!DOCTYPE html> <br> <html><br> <head><br> <meta charset="UTF-8" /><br> <title>11.4 Storing Form Data with Local Storage</title><br> <script><br> <br> // function to read storage and init form<br> function checkStorage() {<br> <br>   // check if local storage available<br>   if (window.localStorage) {<br> <br>     var key, value, field;<br> <br>     // loop through local storage<br>     for (var i = 0; i < localStorage.length; i++) {<br> <br>       // retrieve the key<br>       key = localStorage.key(i);<br> <br>       // set the field from the key<br>       field = document.getElementById(key);<br> <br>       // check for field and assign value<br>       if (field) {<br>         // retrieve the value<br>         value = unescape(localStorage.getItem(key));<br> <br>         // set the field value<br>         field.value = value;<br>       }<br>     }  // end for loop<br>   }  // end local storage check<br> }  // end function<br> <br> // set the localStorage with the changed field<br> function changeField(formField) {<br> <br>   // check if local storage available<br>   if (window.localStorage) {<br> <br>     var key, value;<br> <br>     // set key to form field id<br>     key =;<br>     // set value to form field value<br>     value = escape(formField.value);<br> <br>     // try to set item in local storage<br>     try {<br>       localStorage.setItem(key, value);<br>     } <br>     catch (err) {<br>       if (err.code == QUOTA_EXCEEDED_ERR) {<br>         alert('localStorage ran out of memory.');<br>       }<br>     }<br> <br>   } else {<br>       alert('localStorage is not supported.');<br>   }<br> }<br> <br> // initialize our form from storage<br> window.addEventListener('load',checkStorage,false);<br> <br> </script><br> </head><br> <body><br> <h1>My Form</h1><br> <form id='myForm'><br>   <table><br>     <tr><br>       <td>First Name:</td><br>       <td><input type="text" id="firstName" onchange="changeField(this);" /></td><br>     </tr><br>     <tr><br>       <td>Last Name:</td><br>       <td><input type="text" id="lastName" onchange="changeField(this);" /></td><br>     </tr><br>     <tr><br>       <td>Email:</td><br>       <td><input type="email" id="email" onchange="changeField(this);" /></td><br>     </tr><br>     <tr><br>       <td>Telephone:</td><br>       <td><input type="tel" id="phone" onchange="changeField(this);" /></td><br>     </tr><br>   </table><br> </form><br> </body> <br> </html>

After you enter your first name in the firstName field and tab to the next field, the onchange event will fire for the firstName field. The changeField function will then execute with the form field of firstName passed as a parameter. The changeField function will then store the field data in a key/value pair in localStorage.

The function uses the ID of the form field for the key and the value as the value in the key/value pair. So, if you have Developer Tools open in Chrome when you are doing this, you should now see the key firstName with the value of the text entry you supplied.

To see the real power of localStorage, close your tab or browser window and then reopen it to this form page. When you reopen the page, the checkStorage function will execute on page load. This function is designed to check whether you have previously stored any form information in local storage and retrieve this information. The function will retrieve each key/value pair by looping through the localStorage list, check to see whether there is a form field ID that matches the key name, and if so set the field value to the value retrieved.

In this recipe, you use simple text fields to show the power of localStorage, but this could be used for other types of form inputs as well. The changeField and checkStorage functions would need to be updated to handle different logic for different field types such as a select list or a radio button, but the value could be stored like the regular text input in local storage.

After the page is finished with the stored form information and the form is ultimately submitted to the server, you would ideally want to remove the fields. Besides the removeItem method that you saw before, the storage API provides a method for clearing the entire session or local storage: clear. The clear method takes no parameters nor does it return any result and "clears" all key/value pairs for the page's domain out of the list. The following is an example of the call:


The execution of this line will clear all key/value pairs from the local storage list no matter which page added them or when they were added. Because this is an all-or-nothing type of method, you should be absolutely positive you want to clear the contents of the session storage or the local storage.

In these recipes, you learned about the basics of adding, updating, and removing stored data for a site on the client machine. This assumes the visitor is on a single page interacting with the site at the time. If the stored information was changed from another page in the browser, you have had no way to automatically handle that change on a previously open page. For this more complex scenario, you'll want to consider using the client-side storage API, which provides an event structure for session storage and local storage updates that you can catch and handle on an open page.

This article is excerpted from HTML5 Developer's Cookbook and reprinted with permission of publisher Pearson/Addison-Wesley Professional.

Copyright © 2012 IDG Communications, Inc.

1 2 3 4 5 6 Page 6
Page 6 of 6
It’s time to break the ChatGPT habit
Shop Tech Products at Amazon