I am starting with Javascript, and I have been trying to do the following, I have a table with item in which through inputs I try to calculate the total of each item, regardless of the number of items that exist, however, I only manage to calculate the first item, how can I make it calculate each item, regardless of the number of items found, I greatly appreciate your help, I share my code:
code.html
<table>
<thead>
<tr>
<td>Item</td>
<td>Cantidad</td>
<td>Precio</td>
<td>Subtotal</td>
</tr>
</thead>
<tbody>
<tr>
<td>Manzana</td>
<td><input type="text" class="quantity" onChange="multiplicar();"></td>
<td><input type="text" class="price" onChange="multiplicar();"></td>
<td><input type="text" class="subtotal"></td>
</tr>
<tr>
<td>Pera</td>
<td><input type="text" class="quantity" onChange="multiplicar();"></td>
<td><input type="text" class="price" onChange="multiplicar();"></td>
<td><input type="text" class="subtotal"></td>
</tr>
<tr>
<td>Uva</td>
<td><input type="text" class="quantity" onChange="multiplicar();"></td>
<td><input type="text" class="price" onChange="multiplicar();"></td>
<td><input type="text" class="subtotal"></td>
</tr>
<tr>
<td></td>
<td></td>
<td class="text-right">Total</td>
</tr>
</tbody>
</table>
code.js
<script>
function multiplicar(){
input1 = document.querySelector(".quantity").value;
input2 = document.querySelector(".price").value;
total = parseInt(input1)*parseInt(input2);
document.querySelector(".subtotal").value = total;
}
</script>
#
Update:
function multiplicar(){
var quantity = document.querySelectorAll('.quantity');
var price = document.querySelectorAll('.price');
for(var i = 0; i < quantity.lenght; i++){
console.log(quantity[i].value);
}
for(var i = 0; i < price.lenght; i++){
console.log(price[i].value);
}
}
the problem is in the querySelector. You must use querySelectorAll since you are referring to various items of the class "quantity" and "price". querySelectorAll should be traversed as an array.
Here is the code you can use:
You were using length instead of length, a typing error. What the loop will do is make the calculation of all the inputs that have the class quantity and price and will place it in the corresponding position of subtotal. Since all three elements each have the same number of fields, we only need one loop.