diff --git a/js/index.js b/js/index.js index 75405d6..0e0c565 100644 --- a/js/index.js +++ b/js/index.js @@ -2,22 +2,34 @@ function updateSubtotal(product) { console.log('Calculating subtotal, yey!'); + const priceElement = product.querySelector('.price span'); + const quantityElement = product.querySelector('.quantity input'); - //... your code goes here + const price = parseFloat(priceElement.innerText); + const quantity = parseInt(quantityElement.value); + + const subtotal = price * quantity; + + const subtotalElement = product.querySelector('.subtotal span'); + subtotalElement.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 products = document.querySelectorAll('.product'); // Select all products + let total = 0; - // ITERATION 2 - //... your code goes here + products.forEach(product => { + total += updateSubtotal(product); + }); - // ITERATION 3 - //... your code goes here + // ITERATION 3: Update the total value in the DOM + const totalElement = document.querySelector('#total-value span'); + totalElement.innerText = total.toFixed(2); } // ITERATION 4 @@ -25,18 +37,58 @@ function calculateAll() { 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.remove(); + + calculateAll(); +} + +function addRemoveListeners() { + const removeBtns = document.querySelectorAll('.btn-remove'); + removeBtns.forEach(button => { + button.addEventListener('click', removeProduct); + }); } // ITERATION 5 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; + const price = parseFloat(priceInput.value).toFixed(2); + + if (!name || price <= 0) { + alert('Please enter valid product details'); + return; + } + + const tableBody = document.querySelector('#cart tbody'); + const newRow = document.createElement('tr'); + newRow.classList.add('product'); + newRow.innerHTML = ` +