JSFiddle - React, Tailwind, and code Playground
by Kriti
HTML
Add Book: <input type="text" id="bookName">
<button id="addButton">Add Book</button>
<button id="remButton">Remove Book</button><br><br>
Search: <input type="search" id="search"> <br><br>
<div id="storedBooks"> </div>
JavaScript
// HTML Page to add books to local storage
localStorage.clear(); //to clear localStorage
// Click "Add to Storage" to add a book to the #stored element
// Click "Remove from Storage" to remove the last element from localStorage and the #stored element
//localStorage.clear(); //run this to clear localStorage
var totalItems = localStorage.length,
stored = document.getElementById('storedBooks'),
addBooks = document.getElementById('addButton'),
remBooks = document.getElementById('remButton');
addBooks.addEventListener('click', addToStorage);
remBooks.addEventListener('click', removeStorage);
updateStorage(); // adds stored timestamps to #stored div
function updateStorage(){
// Reset/update innerHTML for #stored div
stored.innerHTML = "Books in the List: <br>"
for(item in localStorage) {
var obj = localStorage[item];
stored.innerHTML += obj + '<br>';
}
}
function addToStorage(event) {
// Create a new localStorage property and assign its value
var propName = 'item' + totalItems;
localStorage.setItem( propName, document.getElementById("bookName").value );
totalItems = localStorage.length;
// Add new value to #stored element
var value = localStorage[propName];
stored.innerHTML += value + '<br>';
}
function removeStorage() {
// Remove the latest property from localStorage
var propName = 'item' + (totalItems - 1);
localStorage.removeItem(propName);
totalItems = localStorage.length;
// Update html to reflect changes
updateStorage();
}