0
I need to make sure that by clicking the "REMOVE" button the removeChild function removes exactly the product on which the REMOVE button is linked.
Currently, everything is fine but I know that in this code the product[0] makes only the element index 0 of the array (Htmlcollection) is deleted, no matter which button "REMOVE" I click. HOW DO I make it to delete only the specific product??? Follows code ....
function removeProduct(event) {
var parent = document.getElementsByTagName('tbody')[0];
var product = document.getElementsByClassName('product');
if (parent.removeChild(product[0])){
calculateAll();
}
}
window.addEventListener('load', () => {
const calculatePricesBtn = document.getElementById('calculate');
calculatePricesBtn.addEventListener('click', calculateAll);
const removeProductsBtn = document.getElementsByClassName('btn btn-remove');
for(var i=0; i<removeProductsBtn.length; i++){
removeProductsBtn[i].addEventListener('click', removeProduct);}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="./css/style.css" />
<title>Ironhack Cart</title>
</head>
<body>
<h1>Ironhack Cart</h1>
<table id="cart">
<thead>
<tr>
<th>Product Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="product">
<td class="name">
<span>Ironhack Rubber Duck</span>
</td>
<td class="price">$<span>25.00</span></td>
<td class="quantity">
<input type="number" value="0" min="0" placeholder="Quantity" />
</td>
<td class="subtotal">$<span>0</span></td>
<td class="action">
<button class="btn btn-remove">Remove</button>
</td>
</tr>
<tr class="product">
<td class="name">
<span>Ironhack Beach Towel</span>
</td>
<td class="price">$<span>12.50</span></td>
<td class="quantity">
<input type="number" value="0" min="0" placeholder="Quantity" />
</td>
<td class="subtotal">$<span>0</span></td>
<td class="action">
<button class="btn btn-remove" id="butaozinho">Remove</button>
</td>
</tr>
<!-- Iteration 2: Add more products here -->
</tbody>
<tfoot>
<tr class="create-product">
<td>
<input id='nomeProduto' type="text" placeholder="Product Name" />
</td>
<td>
<input id='precoUnitario' type="number" min="0" value="0" placeholder="Product Price" />
</td>
<td></td>
<td></td>
<td>
<button id="create" class="btn">Create Product</button>
</td>
</tr>
</tfoot>
</table>
<p class="calculate-total">
<button id="calculate" class="btn btn-success">Calculate Prices</button>
</p>
<h2 id="total-value">Total: $<span>0</span></h2>
<script type="text/javascript" src="./js/index.js"></script>
</body>
</html>
Utilize
function removeProduct(event) { event.target.parentElement.parentElement.remove(); }
. This code will take the element that was clicked, capture the granny element (tr) and remove it.– Valdeir Psr