practice-time-shopping-list/scripts/app.js

70 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2022-11-17 20:42:33 +00:00
document.addEventListener('DOMContentLoaded', () => {
const list = [];
const form = document.querySelector('.shopping-form');
const itemInput = document.querySelector('.shopping-form-item-input');
const quantityInput = document.querySelector('.shopping-form-quantity-input');
const incrementButton = document.querySelector('.shopping-form-increment-button');
const decrementButton = document.querySelector('.shopping-form-decrement-button');
const items = document.querySelector('.shopping-items')
incrementButton.addEventListener('click', incrementQuantity)
decrementButton.addEventListener('click', decrementQuantity)
form.addEventListener('submit', addItemToList)
function incrementQuantity() {
const currentValue = parseInt(quantityInput.value);
const newValue = currentValue + 1;
quantityInput.value = newValue;
}
function decrementQuantity() {
const currentValue = parseInt(quantityInput.value);
const newValue = currentValue - 1;
if (newValue > 0) {
quantityInput.value = newValue;
}
}
function addItemToList(event) {
event.preventDefault();
const itemName = event.target['item-name'].value;
const itemQuantity = event.target['item-quantity'].value;
if (itemName !== '') {
const item = {
name: itemName,
quantity: itemQuantity
};
list.push(item);
renderListItems();
resetInputs();
}
}
function renderListItems() {
let itemsStructure = '';
list.forEach((item) => {
itemsStructure += `
<li class='shopping-item'>
<span>${item.name}</span>
<span>${item.quantity}</span>
</li>
`;
});
items.innerHTML = itemsStructure;
}
function resetInputs() {
itemInput.value = '';
quantityInput.value = '1';
}
})