Archive | June, 2012

How to store and retrieve data from HTML5 localStorage

29 Jun

<a href=”#” onclick=”SetData();”>
Set Data
</a>
<br />

<a href=”#” onclick=”ReadData();”>
Read Data
</a>
<script type=”text/javascript”>
var dcollection = [];
var data = {
id: “”,
title: “”
}
var indexcounter = 1;
function SetData() {
if (typeof (localStorage) != ‘undefined’) {
try {
var key = “key-” + indexcounter;
data.id = indexcounter
data.title = “Title Number -” + indexcounter;
localStorage.setItem(key, JSON.stringify(data));
indexcounter++;
}
catch (e) {
alert(e.toString());
localStorage.clear();
}
}
}

function ReadData() {

if (typeof (localStorage) != ‘undefined’) {
if (localStorage != null) {
var dlength = localStorage.length;
for (i = 0; i < localStorage.length ; i++) {
var key = localStorage.key(i);
var fromlocaldb = localStorage.getItem(key);
var x = JSON.parse(fromlocaldb);
document.write(x.id + “<br/>”);
document.write(x.title + “<br/>”);
}
}
}

}

</script>

Advertisements