rasti.hil@hilandco.com +41 79 367-9677

Monday, 1 November 2010

HTML5 localstorage()

Here is a simple source code for showing how to use localstorage().
Please see the comments in source for explanation.

<!DOCTYPE HTML>
<html>
<head>
<title>localStorage()</title>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
</head>

<body>
<!-- create input elements -->
E-mail: <input type="email" name="user_email" id="email"/ > <br />
First Name: <input type="text" name="f_name" id="fname"/ > <br />
Last Name: <input type="text" name="l_name" id="lname"/ > <br />


<input type="submit" id="submit" />   <input type="button" value="Remove localstorage" id="reset" />
<br /><br />
<!-- show inserted values -->
<div id="show"></div>

<script> 
$(function() {

  
   var edit = document.getElementById('submit');
   var reset = document.getElementById('reset');

  $(edit).click(function() {
 // get data
   var email = document.getElementById('email').value;
 var fname = document.getElementById('fname').value;
 var lname = document.getElementById('lname').value;
 
 var newDate = new Date();
 var itemId = newDate.getTime();
 var values = new Array();
 
 //push each value into our values array
 values.push(email); 
 values.push(fname);
 values.push(lname);
 
 // check if localStorage is supported by browser
 if (typeof(localStorage) == 'undefined' ) {
 alert('Your browser does not support HTML5 localStorage. Try upgrading.');
 }else{
  //store the item in the database
  try {
   localStorage.setItem(itemId, values.join(";")); 
   window.location.href=window.location.href;
  } catch (e) {
   if (e == QUOTA_EXCEEDED_ERR) {
    alert("Quota exceeded!");
   }
  }
 
 }
  });
  
  // when the page loads
  var innerhtml;
  innerhtml ="<table border=\"1\"><tr><td>Email</td><td>Firstname</td><td>Lastname</td></tr>";
  for (i=0;i<localStorage.length;i++){
   var itemKey = localStorage.key(i);
 var values = localStorage.getItem(itemKey); 
 //values currently look like 'name@organization;firstname;lastname' so split them
 values = values.split(";");
 var emails = values[0];
 var fnames = values[1];
 var lnames = values[2];
 innerhtml = innerhtml + "<tr><td>" + emails + "</td><td>" + fnames + "</td><td>" + lnames + "</td></tr>";
  }
   innerhtml = innerhtml + "</table>";
   document.getElementById("show").innerHTML=innerhtml;
 // clear local database
   $(reset).click(function() {
 localStorage.clear();
 window.location.href=window.location.href;
  }
  )
 
  
});</script>
</body>
</html>

No comments: