practice-time-shopping-list/main.js
2022-11-08 14:50:32 -03:00

69 lines
1.8 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () => {
const list = [];
const form = document.querySelector(".shopping-form");
const inputItem = document.querySelector(".shopping-form-item-input");
const quantityInput = document.querySelector(".shopping-form-quantity-input");
const incrementBtn = document.querySelector(
".shopping-form-increment-button"
);
const decrementBtn = document.querySelector(
".shopping-form-decrement-button"
);
const items = document.querySelector(".shopping-items");
incrementBtn.addEventListener("click", increment);
decrementBtn.addEventListener("click", decrement);
form.addEventListener("submit", addItemToList);
function increment() {
const currentValue = Number(quantityInput.value);
const newValue = currentValue + 1;
quantityInput.value = newValue;
}
function decrement() {
const currentValue = Number(quantityInput.value);
const newValue = currentValue - 1;
if (newValue > 0) {
quantityInput.value = newValue;
}
}
function addItemToList(e) {
e.preventDefault();
const itemName = e.target["item-name"].value; /* name do input */
const itemQuantity = e.target["item-quantity"].value;
if (itemName !== "") {
const item = {
name: itemName,
quantity: itemQuantity,
};
list.push(item);
renderListItems();
resetInputs();
}
}
function renderListItems() {
let itemsStructure = "";
list.forEach(function (item) {
itemsStructure += `
<li class="shopping-item">
<span>${item.name}</span>
<span>${item.quantity}</span>
</li
`;
});
items.innerHTML = itemsStructure;
}
function resetInputs() {
inputItem.value = "";
quantityInput.value = 1;
}
});