var grocery_array = []; /* * This function will return a random number * param min : minimum limit of the range (inclusive) * param max: maximum limit of the range (inclusive). * returns : Random integer within specified limits. */ function randint(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function clear_input() { document.getElementById("new_item_input").value = ""; } function addItemToList(item) { grocery_array.push(item); localStorage.setItem("grocery_list", JSON.stringify(grocery_array)); let item_box = document.createElement("div"); item_box.classList.add("grocery_item"); let item_name_container = document.createElement("span"); item_name_container.classList.add("grocery_item_name"); item_name_container.textContent = item; let item_button = document.createElement("button"); item_button.innerHTML = ""; item_button.onclick = (ev) => { let parent_div = ev.target.parentElement.closest("div"); let item_name; var children = parent_div.childNodes; for (var i = 0; i < children.length; i++) { console.log(children[i]); if (children[i].tagName == "SPAN") { item_name = children[i].textContent; break; } } grocery_array = grocery_array.filter((value) => value != item_name); localStorage.setItem("grocery_list", JSON.stringify(grocery_array)); parent_div.remove(); }; item_box.appendChild(item_button); item_box.appendChild(item_name_container); document.getElementById("grocery_list").appendChild(item_box); } function addNewItemToList() { let input = document.getElementById("new_item_input"); if (input.value === "") return; let item = input.value; input.value = ""; // quantity let quantity = document.getElementById("new_item_quantity").value; // unit let e = document.getElementById("new_item_unit"); let text = e.options[e.selectedIndex].text; switch (text) { case "L": item = "" + quantity + (quantity == 1 ? " liter of " : " liters of ") + item; break; case "KG": item = "" + quantity + (quantity == 1 ? " kilogram of" : " kilograms of ") + item; break; default: item = "" + quantity + " " + item; } addItemToList(item); } function restoreList() { JSON.parse(localStorage.getItem("grocery_list")).forEach((element) => { addItemToList(element); }); }