I'm having trouble with my shopping cart code in JavaScript. When I try to log the variables priceElement and quantityElement in the console, nothing shows up even though the tutorial says it should. Additionally, I'm getting an error message 'dairyItemsContainer.getElementById is not a function' when trying to remove an item from the cart. I need assistance with getting the total, price, and remove buttons to stay in sync so that when an item is removed, the total updates accordingly. Can anyone provide guidance?
Check out the HTML for the shopping cart below:
<div>
<table>
<thead>
<tr>
<th>Items</th>
<th>Price</th>
<th>Quantity</th>
<th></th> <!--- remove --->
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Brown Sugar</td>
<td id='price'>€1.59</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
<td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td>Soda Bread</td>
<td id='price'>€2.99</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="1"></td>
<td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td>Milk</td>
<td id='price'>€0.99</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
<td style='float: left;'><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td class='totalFont'>Total</td>
<td class='total'>€5.57</td>
</tr>
</tbody>
</table>
Below is the JavaScript code for handling the shopping cart:
var removeCartItems = document.getElementsByClassName("buttonRemoved");
console.log(removeCartItems);
for (var i = 0; i < removeCartItems.length; i++) {
var button = removeCartItems[i];
button.addEventListener("click", function (event) {
var buttonClicked = event.target;
buttonClicked.parentElement.parentElement.remove();
updateTotal();
});
}
function updateTotal() {
var dairyItemsContainer = document.getElementsByClassName("dairyItems")[0];
var cartRows = dairyItemsContainer.getElementById("dairyTotalHelp");
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i];
var priceElement = cartRow.getElementsByClassName("price")[0];
var quantityElement = cartRow.getElementsByClassName("quantity")[0];
console.log(priceElement, quantityElement);
}
}