Bullet Proof Forms Using Local Storage

Many times we have experienced the frustration to fill a very long form on buying tickets for a concert or when we are booking a flight, and when we are going to submit the form, browser crashes, the internet connection fails or whatever happens that do not let you send the form and erase what several minutes of tedious work has taken to achieve. This article will deliver a general idea about Local Storage and its potential, then we are going to make forms which will keep user data in his browser to make a nice user experience.

What is Local Storage?

Cookies have been used in order to store and retrieve pairs of values with some status of the client´s system. When the user visits again our site, its preferences can be stored. Local Storage can do the same, with the advantage of getting the information from the user agent and not including another elements in every server request like cookies do. Local Store attribute is the capacity of a browser of keeping information in a pair of keys and values. This operation of keeping data locally is done via Javascript.

Which are the advantages of Local Storage?

  • Local Storage keeps data with no expiration date local, which you can access it, delete or replace it.
  • Plus consider that information persists in your browser, even if it is closed or refreshed.
  • No data is transmitted to the server in any manner.
  • Moreover Local Storage can keep the status of an application, so user preferences can be kept and at the same time avoiding the use of cookies.
  • Preventing that a user get frustrated in case of filling a long form and a problem could arised.
  • Five megabytes of storage against 4kb of a cookie
  • Data is stored as strings. It could be considered a limitation, but Local Storage can be parse as Json

Properties

Local Storage has different methods to perform an action with data and they will be listed below with an example:

setItem

For an specific name of store unit (it is recommended you use a descriptive one) you are assigning a value. In this case, to the name “bar” the value “foo” is assigned. If you set again a value to a key, the second value will be the one stored and the previous eliminated.

localStorage.setItem(“bar”,”foo”);

You can do the same using an index system:

localStorage.setItem[“bar”] = foo;

getItem

This method is used in order to retrieve a value from a specific key:

localStorage.getItem(“bar”);

Taking into account the previous example the value retrieved should be “foo”. Furthermore, it could be written like this too:

localStorage.getItem[“bar”];

If the value received is equal to “null” the value is an empty string.

removeItem / delete

This particular method is used in order to erase the key and its value. It can be used in this way: localStorage.removeItem(“bar”) or delete localStorage[“bar”];

In both cases the item is removed from Local Storage.

Clear

This property is focus on erasing the whole Local Storage data:

localStorage.clear();

The difference with removeItem, is that the previous one focus on eliminating data binded to specific pair of key/value, in the other hand clear method erased all the data stored.

Length

Length attribute retrieves the number of key/values of certain data stored:

localStorage.length();

It is very useful in order to loop over an array of data stored which can be accessed by key(i) as the example below:

for (var i = 0; i < localStorage.length; i++) {
 var name = localStorage.key(i);
 var dataStored = localStorage.getItem(name);
 // do something with the key and value on this page
}

Event Storage

This is a bunch of properties related to the moment which Local Storage is modified. These elements are:

  • key: the named key that a value is assigned, modified or erased.
  • newValue:  it is the new value added to the key
  • oldValue: it is the value overwritten
  • storageArea: this gets the storage object of the current document.
  • url: it stores the url that Local Storage was affected.

To have a more detailed idea of how this property works, I recommend reading W3C specification

Local Storage in Forms

Now that we have set an idea regarding Local Storage, we are going to depict in which manner we should serve our self using it in forms. As we mentioned previously, forms are a great field to apply Local Storage because many things on the web are done using this mean of communication. From sending an e-mail to a company to purchase a product, or booking a hotel or flight and many daily tasks, the only one thing in common among these tasks is a web contact form.

Everybody knows how difficult is to persuade a customer to start using our service or selling our product. So it is recommended to save customer choices till they can finish the whole process, because there are many reasons which can interrupt the form sending, so to avoid losing a potential customer Local Storage can save the vital information  our customer filled and in a second attempt achieve sending the form.

Three important considerations to have in mind:

  1. Local Storage only work locally in the same navigator. So if your user access the page with another computer or browser, her or his data will be not stored.
  2. It is recommended if you are managing an online shop to avoid storing credit card data in order to keep your customer´s payment data safe.
  3. We are focused on this article to apply this feature in forms, but there are lots of uses out there.

Now we have set the importance of using this feature in forms we are going to start creating a contact page which never forgets our customer data till the form is submitted. The process we should go through is the following:

  1. Check if Local Storage is supported by the browser using Modernizr.
  2. Storing information (localStorage.setItem() ).
  3. Check if information is stored and retrieved it to the inputs and text area (localStorage.getItem() ).
  4. Clear the information on submit (localStorage.removeItem() ).

Here is the script we are using for the example below:

var datumStored = {
   $name: $("#name").val(), //Selectioning inputs and textarea values
   $email: $("#email").val(),
   $message: $("#message").val(),

  init: function(){

    /*Checking if the browser support Local Storage feature*/
    if(Modernizr.localstorage){

        /*True calls the function to get the inputs and textarea data*/
        datumStored.datumGetter();

    }else {

        //False opens an alert box 
        alert("Your browser does not support localStorage");

    };
  },

  datumGetter: function(){

    /*Each input and textarea´s value is grabbed on key up event, in order t grab it during typing, and set the localStorge item.  */     
    $("#name").keyup(function(){

        datumStored.$name = $(this).val();      
        localStorage.setItem("name", datumStored.$name);

    });

    $("#email").keyup(function(){

       datumStored.$email = $(this).val();   
       localStorage.setItem("email", datumStored.$email);

    });

    $("#message").keyup(function(){

        datumStored.$message = $(this).val();
        localStorage.setItem("message", datumStored.$message);
    });

      //Here we call the next part of our functionality
      datumStored.datumAssembler();

  },

  datumAssembler: function(){

    /*First we check if the value is empty, then if there is a localStorage item, we recover  and establish it as input or text area value.*/

    /*In this manner if a user who was filling down our form, and due to a browser problem the form is not sent, we prevent user´s frustration on filling down the form again*/
    if(datumStored.$name == ""){

      //getItem methods recovers the data stored
      var nameStored = localStorage.getItem("name");
      $("#name").val(nameStored);

    };

    if(datumStored.$email == ""){

        //getItem methods recovers the data stored    
        var emailStored = localStorage.getItem("email");
        $("#email").val(emailStored);

    };

    if(datumStored.$message == ""){

        //getItem methods recovers the data stored
        var messageStored = localStorage.getItem("message");
        $("#message").val(messageStored);

    datumStored.eraseStore();

    };

  },

  eraseStore: function(){

    $("#contact").submit(function(){

          /*If the form is sent, data do not need to be stored, that´s why we clean the storage after sending the form */
          localStorage.removeItem("name");
          localStorage.removeItem("email");
          localStorage.removeItem("message");

    });

  }

};

datumStored.init();

In order to test this feature, you should include some data on the form and then, refresh the browser  and the data you had written is saved in Local Storage. Below the working example:

See the Pen zbhKA by eWebDesign (@ewebdesign) on CodePen.0

Crossbrowser issues

Local Storage is supported in all mayor browsers. Regarding IE universe from IE8 + this feature is supported, but as everyone  who works in this field knows many requirements still ask for supporting IE 6 and 7. For both cases, you can rely on store.js script which falls back on userData behavior.

Conclusion

Local Storage is a great tool for keeping customer´s data on forms, it lets us create  an experience which can hold information in any situation, with the confidence that data can be used when it  is needed. This feature can be used for keeping user preferences on a site, and the same time sending http cookies to the web features museum.

Reliable and useful, we must consider to include this feature in all our forms to let the customer have a change to avoid frustrating him and speed up any process. However we should be careful with sensitive data as credit cards numbers and at the same time erase the stored data when the process reaches its end.

Further Readings

Hot Deals & Offers!

Find enormous discounts and hot offers for many useful services and products
(designmodo, creative-tim, themify and more)

Check Out Now
Sponsors
No comments yet, leave yours
Leave a Comment