I have a table with some columns for typing values and I need to add the total of these values in an end column.
The sum is easy to do, however the table and dynamics are generated several lines, and when I try to add the columns again in the new line, I am also adding the result of the previous lines.
I think I should have to set my javascript call as default for the new calculation line but I'm not sure how to do it see example
Note that in the first column the total adds up correctly, in the second it adds some 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 the 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 that if I define that with each line the sum must be started from scratch I solve the problem, but I did not identify how to do it