forked from M3-Academy/practice-time-shopping-list
feat: Finalizado js #6
68
main.js
68
main.js
@ -0,0 +1,68 @@
|
||||
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;
|
||||
}
|
||||
});
|
Loading…
Reference in New Issue
Block a user