1
In my system, I dynamically send columns with dates based on a parameter received, building a table where in X I have products and Y I have the amount that comes in each package, date list in th
with inputs to enter how many the customer would like to receive on each date, and the total.
The problem is that when I type the quantity, it accumulates, ignores if I delete the value of one input and enter 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);
}
}
});
Its variable
sum
never reset to zero when you delete all input content. You could put this var sum = 0 inside the$('input').on("keyup", function () {
and I believe I should already solve your problem, but there are more efficient ways to do the same.– Pedro Henrique
@Pedrohenrique I even tried, but as I have inputs x,y. When I activate the function via input X and put value 1, my sum is 1. However, if I call the function through input Y after setting value 1, it will ignore 1, set again to 0 and apply the value only of input Y
– Rafael Barbosa
I understand, what you can do is the following, create a function that has as its sole objective, go through all the inputs and calculate the value of each, considering if it is zero. But always calculate all inputs. And within your
$('input').on("keyup", function () {
you just make the call from this function.– Pedro Henrique