diff --git a/index.html b/index.html index 752a993..824c68e 100644 --- a/index.html +++ b/index.html @@ -35,20 +35,21 @@
diff --git a/js/index.js b/js/index.js index 75405d6..b808b87 100644 --- a/js/index.js +++ b/js/index.js @@ -1,39 +1,99 @@ // ITERATION 1 - function updateSubtotal(product) { console.log('Calculating subtotal, yey!'); - //... your code goes here + const priceElement = product.querySelector('.price span'); + + const quantityElement = product.querySelector('.quantity input'); + + const price = parseFloat(priceElement.innerHTML); + const quantity = parseInt(quantityElement.value); + + const subtotal = price * quantity; + + const subtotalElement = product.querySelector('.subtotal span'); + + subtotalElement.innerHTML = subtotal.toFixed(2); + + return subtotal; } function calculateAll() { - // code in the following two lines is added just for testing purposes. - // it runs when only iteration 1 is completed. at later point, it can be removed. - const singleProduct = document.querySelector('.product'); - updateSubtotal(singleProduct); - // end of test + const products = document.querySelectorAll('.product'); - // ITERATION 2 - //... your code goes here + let total = 0; - // ITERATION 3 - //... your code goes here + products.forEach((product) => { + total += updateSubtotal(product); + }); + + const totalValueElement = document.querySelector('#total-value span'); + totalValueElement.innerHTML = total.toFixed(2); } -// ITERATION 4 +const calculateButton = document.getElementById('calculate'); +calculateButton.addEventListener('click', calculateAll); +// ITERATION 4: Removing Products function removeProduct(event) { const target = event.currentTarget; - console.log('The target in remove is:', target); - //... your code goes here + + const productRow = target.closest('.product'); + + productRow.parentNode.removeChild(productRow); + + calculateAll(); } -// ITERATION 5 +function setupRemoveButtons() { + const removeButtons = document.querySelectorAll('.btn-remove'); + removeButtons.forEach((button) => { + button.addEventListener('click', removeProduct); + }); +} + +setupRemoveButtons(); +// ITERATION 5: Adding New Products function createProduct() { - //... your code goes here + const nameInput = document.getElementById('new-product-name'); + const priceInput = document.getElementById('new-product-price'); + + const name = nameInput.value; + const price = parseFloat(priceInput.value); + + if (!name || isNaN(price) || price <= 0) { + alert('Please enter a valid product name and price.'); + return; + } + + const newRow = document.createElement('tr'); + newRow.classList.add('product'); + newRow.innerHTML = ` +