Skip to content

Commit 6a58001

Browse files
committed
updatable menu
1 parent 6215372 commit 6a58001

File tree

1 file changed

+56
-5
lines changed

1 file changed

+56
-5
lines changed

15 - LocalStorage/index-START.html

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,66 @@ <h2>LOCAL TAPAS</h2>
2020
<li>Loading Tapas...</li>
2121
</ul>
2222
<form class="add-items">
23-
<input type="text" name="item" placeholder="Item Name" required>
24-
<input type="submit" value="+ Add Item">
23+
<input id="newItemBox" type="text" name="item" placeholder="Item Name" required>
24+
<input id="submit" type="submit" value="+ Add Item">
2525
</form>
2626
</div>
2727

2828
<script>
29-
const addItems = document.querySelector('.add-items');
30-
const itemsList = document.querySelector('.plates');
31-
const items = [];
29+
// Check browser support
30+
var hasStorage = false;
31+
if (typeof(Storage) !== "undefined") {
32+
hasStorage = true;
33+
}
34+
// Find Page Elements
35+
var addItems = document.querySelector('.add-items');
36+
var itemList = document.querySelector('.plates');
37+
var newItemBox = document.getElementById('newItemBox');
38+
// Menu Items (possibly from localStorage)
39+
var items = (hasStorage && JSON.parse(localStorage.getItem("menu"))) || [];
40+
var itemsChecked = (hasStorage && JSON.parse(localStorage.getItem("menuChecked"))) || [];
41+
42+
var refreshItemList = function() {
43+
// build the HTML menu list
44+
var plateList = [];
45+
for (var i=0; i < items.length; i += 1){
46+
var ii = i.toString();
47+
plateList.push('<li><input type="checkbox" data-index="' + ii + '" id="item' + ii + '"' + (itemsChecked[i] ? ' checked="checked"' : '') + ' /><label for="item' + ii + '" >' + items[i] + '</label></li>');
48+
}
49+
itemList.innerHTML = plateList.join("");
50+
};
51+
refreshItemList();
52+
53+
var updateStorage = function() {
54+
if (hasStorage) {
55+
localStorage.setItem("menu", JSON.stringify(items));
56+
localStorage.setItem("menuChecked", JSON.stringify(itemsChecked));
57+
}
58+
};
59+
60+
var menuFormSubmit = function(e){
61+
// Handle adding a new menu item to the page
62+
e.preventDefault();
63+
items.push(newItemBox.value);
64+
itemsChecked.push(false);
65+
updateStorage();
66+
newItemBox.value = '';
67+
refreshItemList();
68+
};
69+
70+
var menuClick = function(e){
71+
if (e.target.type === "checkbox") {
72+
var index = parseInt(e.target.dataset.index);
73+
itemsChecked[index] = !itemsChecked[index];
74+
updateStorage();
75+
}
76+
};
77+
78+
// Event Handlers
79+
addItems.addEventListener('submit', menuFormSubmit);
80+
itemList.addEventListener('click', menuClick);
81+
82+
// TODO: Add clear-all, (de)/highlight-all buttons. Simple-looking.
3283

3384
</script>
3485

0 commit comments

Comments
 (0)