JavaScript Code to Save and Load a Table Using HTML5 Web Storage
By Stephen Bucaro
HTML version 5 brings us web storage, providing methods to store keyword/value
data pairs in the user's browser. All modern browsers support web storage, you have to go
way back to Internet Explorer version 7 and Chrome, Firefox, and Safari version 3 before
you lose support.
With web storage you can store up to 5MB of data in the user's browser. All data that was
stored by a specific domain shares the same storage area, so you can share data between
multiple pages. The data is persistent on the client's machine, so you can use it to store
data for a long time.
Web storage cannot hold binary data, only strings. If you want to store numerical data,
you can use the JavaScript built-in methods parseInt() or parseFloat to
convert string data into integers or floats that can then be used in calculations.
Web storage provides sessionStorage to preserve data only while the user's browser is
accessing your site, and localStorage which preserves data (almost) permanently. Both
interfaces use the same methods, only the prefix is different, so these examples will use
only localStorage.
The primary Web Storage methods are setItem(key, value), which adds a key/value pair
to web storage, and getItem(key) which retrieves a value based on its key. In this
example I show you how to create a user-editable table, how to use setItem to store
the table, and how to use getItem to rebuild the table to present it to the user on
their next visit to your site.
Saving the Table
Shown below is the JavaScript to save an html table to Web Storage. Paste this code into
the <head> section of your web page.
<script>
function storeTable()
{
var table = document.getElementById("myTable");
localStorage.setItem("rows", table.rows.length);
localStorage.setItem("cols", table.rows[0].cells.length);
for(var r = 0, n = table.rows.length; r < n; r++)
{
for (var c = 0, m = table.rows[r].cells.length; c < m; c++)
{
var keyword = r + "," + c;
var value = table.rows[r].cells[c].innerHTML;
localStorage.setItem(keyword, value);
}
}
}
</script>
Note in the code that first I use the document.getElementById method to get the
configuration of the table, e.g. how many rows and columns. I use the localStorage.setItem
method to store two keyword/value pairs in Web Storage (rows/n and cols/n).
I then use the rows and columns information retrieved by the document.getElementById
method to loop through the table's rows and columns and use the .innerHTML method to
retrieve each cells contents. I use the localStorage.setItem method to store this data as
keyword/value pairs in Web Storage.
The keyword part of each keyword/value pair is a string constructed by concatenating the row
number, a comma, and the cell number. The value part of each keyword/value pair is the cells contents.
|