3
I have a table with some columns for typing values and I need to add the total of these values in a final column.
The sum is easy to do, however the table and dynamic and are generated multiple rows, and when I try to re-add the columns in the new row, I am also adding the result of the previous rows.
I believe I should have to set my javascript call as default for the new calculation line but not knowing how to do take the example
Note that in the first column the total sums correctly, in the second it sums right tbm, but adds the value together with the result of the previous field.
The PHP code looks like this:
<?php for ($cont = 1; $cont <= $quantidadeRegistros; $cont++): ?>
<tr>
<?php for ($i = 1; $i < 5; $i++): ?>
<td><input class='form-control calcular' type='text' name='quantidade[]' onkeyup='calcular(<?php echo $cont ?>)' </td>
<?php endfor; ?>
<td>
<input class='form-control' type='text' name='total[]' id='result-<?php echo $cont ?>' readonly />
</td>
</tr>
<?php endfor; ?>
And javascript like this:
$(document).ready(function () {
function calcular(id) {
var campo = 'result-'.concat(id);
var soma = $('.calcular').get().reduce(function (soma, el) {
return (parseInt(el.value, 10) || 0) + soma;
}, 0);
document.getElementById(campo).value = soma;
}
});
I think if I define that at each line the sum should be started from scratch I solve the problem, but I did not identify how to do it
When the calculate function is called?
– BrTkCa
when I type a value into product input. In input there is an onkeyup call='calculate(<? php echo $cont ?>)'
– tkmtts