HTML and CSS Reference
In-Depth Information
<section>
<button type="button" id="btnAdd">Add To Storage</button>
<button type="button" id="btnRemove">Remove from Storage</button>
<button type="button" id="btnClear">Clear Storage</button>
</section>
<div id="storage">
<p>Current Storage Contents</p>
</div>
</body>
</html>
The code in Listing 1-4 creates text boxes to accept a key and a value, respectively. Buttons
let you add items to storage, remove an item, or completely clear the storage. Each capability
is implemented in turn. To display the contents of the storage, the page contains a
div
that
shows the contents of the storage appended to it. The
LoadFromStorage
method is called for
each operation to refresh the page with the data available in the storage. All the following
examples use local storage, but again, they would work the same way with session storage.
If you want to test these examples using session storage, simply replace the
localStorage
reference with a reference to
sessionStorage
.
You first need to implement the
LoadFromStorage
method so that when the page loads,
you can see any items that have already been placed into storage. Enter the following code
into the
LoadFromStorage
function in the script block:
window.onload = function () {
LoadFromStorage();
document.getElementById("btnAdd").onclick = function () {
…
function LoadFromStorage() {
var storageDiv = document.getElementById("storage");
var tbl = document.createElement("table");
tbl.id = "storageTable";
if (localStorage.length > 0) {
for (var i = 0; i < localStorage.length; i++) {
var row = document.createElement("tr");
var key = document.createElement("td");
var val = document.createElement("td");
key.innerText = localStorage.key(i);
val.innerText = localStorage.getItem(key.innerText);
row.appendChild(key);
row.appendChild(val);
tbl.appendChild(row);
}
}
else {
var row = document.createElement("tr");
var col = document.createElement("td");
col.innerText = "No data in local storage.";
row.appendChild(col);
tbl.appendChild(row);
}
Search WWH ::
Custom Search