0
I’m trying to use Javascript to dynamically calculate my prices multiplied by the quantities and result in the total for each row, however it calculates the overall total and plays in the last field of the Total column. As in the picture below:
function calc(){
var prices = new Array();
var quantities = new Array();
var counter = 0;
var total = 0;
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++){
if(elements[i].getAttribute('special') == 'price'){
prices[counter] = parseFloat(elements[i].value);
}
if(elements[i].getAttribute('special') == 'quantity'){
quantities[counter] = parseInt(elements[i].value);
counter++;
}
}//Fim for
for(var i = 0; i < prices.length; i++){
total += (prices[i] * quantities[i]);
}//Fim for
document.getElementById('total').value = total;
}//Fim function
<table border = '2'>
<thead>
<tr>
<th>Preço</th>
<th>Quantidade</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="valor_unitario[]" id="valor_unitario" value="2.50" special="price" /></td>
<td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
<td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
</tr>
<tr>
<td><input type="text" name="valor_unitario[]" id="valor_unitario" value="5.50" special="price" /></td>
<td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
<td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
</tr>
<tr>
<td><input type="text" name="valor_unitario[]" id="valor_unitario" value="1.20" special="price" /></td>
<td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
<td> <input type="text" name="total" class="total" readonly="readonly" onclick="calc();" /> </td>
</tr>
<tr>
<td><input type="text" name="valor_unitario[]" id="valor_unitario" value="9.80" special="price" /></td>
<td><input type="text" name="qnt[]" id="qnt" value="1" special="quantity" /></td>
<td> <input type="text" name="total" id="total" readonly="readonly" onclick="calc();" /> </td>
</tr>
</tbody>
</table>
I saw it, quiet!
– user60252