I am trying to add products to a shopping table, which works well, the problem comes when calculating, between the quantity of the product and the price, however, when changing the quantity, this is not the calculates, I had a certain inconvenience when defining this calculation since the field of #producto-quantity
does not exist previously, but is created later with Javascript, so it is difficult for me to extract its id previously to be able to capture its value, and so can calculate it, I appreciate your help to do this correctly, I share my code below, the error is more specifically in the section commented as: //Create New HTML Element
<div class="container py-5">
<div class="row">
<!-- Product List -->
<div class="col-sm-6">
<h2>Productos <%= link_to 'Nuevo producto', new_product_path, class: "btn btn-sm btn-primary float-right" %></h2>
<table class="table" id="products">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th class="text-right">Opciones</th>
</tr>
</thead>
<tbody>
<tr>
<td class="product-id">1</td>
<td class="product-name">Manzana</td>
<td class="product-price">0.25</td>
<td><button class="add-product btn btn-primary">Agregar</button></td>
</tr>
<tr>
<td class=product-id">2</td>
<td class="product-name">Sandia</td>
<td class="product-price">0.45</td>
<td><button class="add-product btn btn-primary">Agregar</button></td>
</tr>
<tr>
<td class="product-id">3</td>
<td class="product-name">Uva</td>
<td class="product-price">0.25</td>
<td><button class="add-product btn btn-primary">Agregar</button></td>
</tr>
</tbody>
</table>
</div>
<!-- Sale -->
<div class="col-sm-6">
<h2>Venta</h2>
<table class="table" id="shopping-list">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Precio Unit.</th>
<th>Cant.</th>
<th>Precio Total</th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<script>
// Get Product Data
function addProduct(e){
//Get HTML Element
const getElement = e.target.parentElement.parentElement;
const product = {
id: getElement.querySelector('.product-id').textContent,
name: getElement.querySelector('.product-name').textContent,
price: getElement.querySelector('.product-price').textContent
}
// Create New HTML Element
const newElement = document.createElement('tr');
let quantity = 1;
let itemPrice = product.price * quantity;
newElement.innerHTML = '
<td>${ product.id }</td>
<td>${ product.name }</td>
<td>${ product.price }</td>
<td><input type="number" name="quantity" class="product-quantity form-control" step="any" value="${ quantity }" /></td>
<td>${ itemPrice }</td>
<td><a href="" class="remove-item" id="${ product.id }">X</a></td>
';
// Add Product to Shopping List
const shoppingList = document.querySelector('#shopping-list tbody');
shoppingList.appendChild(newElement);
}
// Get All ID Button
let addThis = document.getElementsByClassName('add-product');
for (let i = 0; i < addThis.length; i++){
addThis[i].addEventListener('click', addProduct);
}
</script>