Like us on Facebook and stand a chance to win pen drives!

How to store an array in localStorage

HTML5 LocalStorage
HTML5 LocalStorage

This tutorial assumes that you are already familiar with HTML5  localStorage.

Although HTML5  localStorage is very useful, its usage is restricted to key value mechanism. Key and value is stored in string format despite what we need. For an instance, though you can specify a boolean type (either true or false) as the value, it is stored as a string.

What if we need to store multiple items as the value for a certain key. This can be little bit tricky if you gonna place an array directly as the value. When we scratch the surface of localStorage basic principles this is not possible. However you can come up with your own solutions that might work for you.

This tutorial demonstrates a simple way of handling above problem using json. We gonna store array as a json string. So nothing new here.

First add jQuery library as we are using some jQuery functions.


<script type="text/javascript">
 var favorites_str = localStorage.getItem('my_favorites');
 if(favorites_str == null) {
 favorites = [];
 favorites.push({ "name":"keshi", "id":"6" });
 } else{
 favorites = JSON.parse(favorites_str);
 favorites.push({ "name":"sara", "id":"6" });
 
}
 localStorage.setItem('my_favorites',JSON.stringify(favorites));
 </script>

To verify that above script is functioning please copy and run below script. It will make things easy, if you put this code in  a separate file.

<script type="text/javascript">
 var data = localStorage.getItem('my_favorites');
 if(data == null){
 alert("0 favorites");
 }else{
 favorites = JSON.parse(data);
 $.each(favorites, function(index,item){
 alert(item.name);
 
});
 }
 </script>


0 comments:

Copyright © 2012 The Code Junction.