diff --git a/js/index.js b/js/index.js index 75405d6..b40dbf6 100644 --- a/js/index.js +++ b/js/index.js @@ -1,42 +1,70 @@ -// ITERATION 1 - +// 🚀 ITERATION 1, 2, 3: Calculate Subtotals and Total Price function updateSubtotal(product) { - console.log('Calculating subtotal, yey!'); - - //... your code goes here + const price = parseFloat(product.querySelector('.price span').innerText); + const quantity = parseInt(product.querySelector('.quantity input').value); + const subtotal = price * quantity; + product.querySelector('.subtotal span').innerText = 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 allProducts = document.querySelectorAll('.product'); + let total = 0; - // ITERATION 2 - //... your code goes here + allProducts.forEach((product) => { + total += updateSubtotal(product); + }); - // ITERATION 3 - //... your code goes here + document.querySelector('#total-value span').innerText = total.toFixed(2); } -// ITERATION 4 - +// 🚀 ITERATION 4: Remove Product function removeProduct(event) { - const target = event.currentTarget; - console.log('The target in remove is:', target); - //... your code goes here + const productRow = event.currentTarget.closest('.product'); + productRow.remove(); + calculateAll(); } -// ITERATION 5 - +// 🚀 ITERATION 5: Create New Product function createProduct() { - //... your code goes here + const nameInput = document.querySelector( + '.create-product input[type="text"]' + ); + const priceInput = document.querySelector( + '.create-product input[type="number"]' + ); + const name = nameInput.value.trim(); + 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 = ` +