2.1. Retrieving All Key-Value Pairs and Listing Them in a Table

The following HTML code contains a heading (the h1 element), an empty table that will be filled with the help of JavaScript code, a navigation menu (in the nav element), and a script element containing the JavaScript code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta charset="UTF-8" />
 <title>Phone Number Directory</title>
</head>
<body>
 <h1>Phone Number Directory</h1>
 <table>
  <tbody id="directory"></tbody>
 </table>
 <hr/>
 <nav>
  <ul>
   <li><a href="index.html">Home</a></li>
   <li><a href="add.html">Add an entry</a></li>
   <li><a href="update.html">Update an entry</a></li>
   <li><a href="delete.html">Delete an entry</a></li>
  </ul>
 </nav>
 <script>
  ...
 </script>
</body>
</html>

On this "Home" page of our data management app, the currently stored key-value pairs are retrieved from localStorage and shown as table rows. If localStorage is empty, four test data key-value pairs are created and added to the store. This is done by the following JavaScript code, which forms the content of the script element:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
 // get a handle for accessing the "directory" table body element
 let tableBodyEl = document.getElementById("directory");
 // add some key-value pairs if the store is empty
 if (localStorage.length === 0) {
   localStorage["Bob Jennings"] = "(732) 516-8970";
   localStorage["Jane Anselm"] = "(732) 516-4301";
   localStorage["Tara Helms"] = "(504) 972-3381";
   localStorage["Tom Miller"] = "(282) 664-9357";
 }
 // show the contents of the store
 for (let key of Object.keys( localStorage)) {
   let row = tableBodyEl.insertRow();
   row.insertCell().textContent = key;
   row.insertCell().textContent = localStorage[key];
 }
</script>

Exercise: Open a text editor of your choice (e.g., NotePad++). First copy and paste the HTML code above into your editor, then add the JavaScript code in the script element. Make a folder (e.g. with name "KeyValueStoreExample") and save the content of your editor window in this folder as "index.html". Then go to this folder (e.g., using Windows Explorer) and open the "index.html" file in a browser. You should see a page containing a table with 4 phone directory entries as in Table 1-1 above.