HTML and CSS Reference
In-Depth Information
function OnStoreClick(event) {
var key = $("#keyName").val();
var value = $("#keyValue").val();
storage.setItem(key, value);
$("#tblItems").empty();
for (var i = 0; i < storage.length; i++)
{
$("#tblItems").append("<tr><td>" + storage.key(i) + " = " +
storage.getItem(storage.key(i)) + "</td></tr>");
}
}
function OnClearClick(event) {
storage.clear();
$("#tblItems").empty();
}
This code first stores a reference to the
localStorage
object in a variable:
storage
. This way, you don't
always need to use
window.localStorage
syntax to call methods of the
localStorage
object. Additionally, if
you decide to test
sessionStorage
instead of
localStorage
, you can just change this one line of code, and
the rest of the code automatically uses
sessionStorage
object. Notice how support for
localStorage
is
checked using Modernizr. If you wish to check support for
sessionStorage
, you can use the
Modernizr.
sessionstorage
property instead.
The jQuery
ready
function wires the
click
events of the two buttons (Store Data and Clear Data) with
event-handler functions:
OnStoreClick()
and
OnClearClick()
.
The
OnStoreClick()
event-handler function stores a key-value pair in the
storage
object using the
setItem()
method of the
localStorage
object. It then iterates through all the keys. With every iteration, the
code uses
key()
and
getItem()
to retrieve a key and its value. The key-value pair is then added to the
tblItems
table.
The
OnClearClick()
event-handler function simply removes all the items from the store using
clear()
method.
Storing Numbers, Dates, and Objects
Although the
localStorage
and
sessionStorage
objects allow you to store data, they suffer from a
limitation as far as the data type of items being stored is concerned: all the data is stored as string. Even if
you add values with numeric or date data types, they're still stored as plain strings. This is important
because when you read the data back, you may need to convert it into an appropriate data type. In still
more complex scenarios, you may want to store objects in web storage. Obviously, because web storage
natively supports only string data to be stored, these types of conversions are your responsibility.
Consider the piece of code shown in Listing 7-2.
Listing 7-2.
Storing Numbers in
localStorage
$(document).ready(function () {
var storage = window.localStorage;
storage["number1"] = 10;
storage["number2"] = 20;
var sum1 = storage["number1"] + storage["number2"];
var sum2 = Number(storage["number1"]) + Number(storage["number2"]);