In my system, I dynamically generate columns with dates based on a received parameter, constructing a table where in X I have products and Y have the quantity that comes in each package, date relation in the th
with inputs to type how many the customer would like to receive on each date, and the total.
The problem is that when I type the amount, it accumulates, ignores if I delete the value of one input and type another, that is, if I had the values 2, 3 and 5 in each input, totaling 10, if I delete the value 3 and write 1 it totals 11.
My script below:
var Meses = [];
var IDs = [];
IDs = pID.split(",");
var IDAtual = 0;
Meses.push(mesInicial + "/" + Ano);
while (CountMes < 5 && Diferenca > CountMes) {
CountMes++;
mesInicial++;
if (mesInicial > 12) {
mesInicial = mesInicial - 12;
if (Ano < Ano + 1) {
Ano++;
}
}
Meses.push(mesInicial + "/" + Ano);
}
for (var i = 0, l = Meses.length; i < l; i++) {
$('#NovoCompromisso').find('tr:first').each(function () {
$(this).append("<th class='text-center'>" + Meses[i] + "</th>");
});
if ((l - 1) == i) {
IDAtual = 0;
}
$('#NovoCompromisso').find('tr:not(:first)').each(function () {
$(this).append("<td ><input type='number' class='qtdItem' data-id='" + IDs[IDAtual] + "' /></td>");
IDAtual++;
});
}
$('#NovoCompromisso').find('tr:first').each(function () {
$(this).append("<th class='text-center'>Total</th>");
});
$('#NovoCompromisso').find('tr:not(:first)').each(function () {
$(this).append("<td><input type='number' class='totalQTD' disabled='disabled' value='0' /></td>");
});
Below is the most important part, where I make the sum
var sum = 0;
$('input').on("keyup", function () {
for (var i = 0, l = IDs.length; i < l; i++) {
if ($(this).attr('data-id') == IDs[i]) {
if ($(this).val() != "") {
sum += parseFloat($(this).val());
}
var Total = $(this).parent().parent().find('.totalQTD').val(sum);
}
}
});