Merge pull request 'feat: Finalizado js' (#6) from feature into main

Reviewed-on: #6
This commit is contained in:
ThiagoDutraSampaioLeite 2022-11-08 17:51:14 +00:00
commit a32fd546ce

68
main.js
View File

@ -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;
}
});