hmw3 "I finally figured it out!"
by Ken Sprague
HTML
<h1>Shopping List</h1>
<form name="theForm" id="theForm">
<label for="itemName">Item Name</label><input type="text" id="itemName" autofocus><br>
<label for="itemQuantity">Quantity</label><input type="text" id="itemQuantity"><br>
<br>
<input type="submit" id="addButton" value="Add Item">
<span id="message"></span>
</form>
<h2>Items:</h2>
<button id="clearStorage" class="hide">Clear Local Storage</button>
<!-- Dynamically Populate List -->
<ul id="itemList"></ul>
JavaScript
console.clear();
var items = [];
//item constructor function
function Item(name, quantity) {
this.name = name;
this.quantity = quantity;
this.display = function() {
return `${this.quantity} ${this.name}`;
}
}
//function to persist storage
function persistItems() {
localStorage.setItem('persistedItems', JSON.stringify(items));
}
//funtion to display items
function displayItems() {
//clear existing items from page
document.getElementById('itemList').innerHTML = '';
//loop through items and display
for(var item in items) {
var li = document.createElement('li');
var txt = document.createTextNode(items[item].display());
li.appendChild(txt);
document.getElementById('itemList').appendChild(li);
}
persistItems();
}
function addItem(e) {
e.preventDefault();
var itemName = document.getElementById('itemName').value;
var itemQuantity = document.getElementById('itemQuantity').value;
if (itemName !== '' && itemQuantity !== '') {
items.push(new Item(itemName, itemQuantity));
displayItems();
//reset input fields
document.getElementById('itemName').value = ' ';
document.getElementById('itemQuantity').value = ' ';
//set cursor in comicTitle field with focus
document.getElementById('itemName').focus();
} else {
alert('Please add Name and Quantity.');
}
}
//function to clear storage
function promptToClearStorage() {
// confirm dialog
var clearStorage = confirm('Would you like to clear your local storage?');
if (clearStorage) {
//clear localstorage
localStorage.removeItem('persistedItems');
console.log('Local Storage has been cleared.');
}
}
//check to see if local storage is supported
if (typeof(Storage) !== "undefined") {
console.log('Local Storage is supported.');
}
//try to get Comics from storage
var persistedItems = localStorage.getItem('persistedItems');
//check to see if data is in storage
if (persistedItems !== null) {
persistedItems =...