diff --git a/index.html b/index.html index 752a993..6d9b0ab 100644 --- a/index.html +++ b/index.html @@ -33,21 +33,34 @@
diff --git a/js/index.js b/js/index.js index 75405d6..7c090d7 100644 --- a/js/index.js +++ b/js/index.js @@ -3,21 +3,31 @@ function updateSubtotal(product) { console.log('Calculating subtotal, yey!'); - //... your code goes here + const price = product.querySelector('.price span'); + const quantity = product.querySelector('.quantity input'); + + const priceValue = parseFloat(price.innerHTML); + const quantityValue = parseFloat(quantity.value); + + const subtotalValue = priceValue * quantityValue; + + const subtotal = product.querySelector('.subtotal span'); + subtotal.innerHTML = subtotalValue.toFixed(2); + + return subtotalValue; } 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 - // ITERATION 2 - //... your code goes here + const products = document.getElementsByClassName('product'); + let total = 0; + for (let i = 0; i < products.length; i++) { + total += updateSubtotal(products[i]); + } // ITERATION 3 - //... your code goes here + const totalValue = document.querySelector('#total-value span'); + totalValue.innerHTML = total.toFixed(2); } // ITERATION 4 @@ -25,18 +35,66 @@ function calculateAll() { function removeProduct(event) { const target = event.currentTarget; console.log('The target in remove is:', target); - //... your code goes here + + // Find parent and remove it: + const productRow = target.closest('.product'); + productRow.parentNode.removeChild(productRow); + + // Recalculate + calculateAll(); } // ITERATION 5 function createProduct() { - //... your code goes here + const nameInput = document.querySelector('.new-product-name'); + const priceInput = document.querySelector('.new-product-price'); + + const nameValue = nameInput.value; + const priceValue = parseFloat(priceInput.value).toFixed(2); + + if (nameValue.trim() === '' || priceValue <= 0) { + alert('Please enter a valid product name and price.'); + return; + } + + const productRow = document.createElement('tr'); + productRow.classList.add('product'); + + productRow.innerHTML = ` +