Dynamically add and remove fields with sum and multiplication of values

Asked

Viewed 354 times

1

I have a tab, where the user should put the amount and value of each item. He can add as many items as he wants. At the bottom of the page, it will show the total result of the sum of all possible lines that the user adds.

See Fiddle next to understand better.

Jsfiddle: https://jsfiddle.net/f0aggozk/1/

This structure is practically finished. The only problem that is happening is that when adding a new field, if any of the values are empty, the total value displayed is empty. I believe that it is necessary to make the calculation for each one of the lines, and add up the value of all the lines.

  • need to be with pure jquery? There are some frameworks that make this quite easy.

  • I am open to alternatives, but I believe that my code is only a few details to run it without bugs.

  • The problem is that when you add a new line you are zeroing out? If so, your validation to set the total to zero on line 46 this zeroing out the total. If the total of the last line is zero, you are zeroing out the total. I made a small adjustment see here if it is ok: https://jsfiddle.net/5z0qavps/1/.

  • Actually, adding a new line was not the problem. The calculation occurred when changing the input. By keeping it empty or deleting it, the bug of zeroing everything happened. But the validation you added really solved it. Add as answer to the question, please. :)

  • @Mauroalves how good it worked, I added in response.

  • Thank you @cbonomini

Show 1 more comment

1 answer

2


The validation where you are zeroing the total, is in the wrong place.

You should validate after the loop that summed, and test if amount_sum is zero to zero. And test the total only to confirm whether it will take into account the total sum.

function somarValores() {
    var amount_sum = 0;
    //calculate total worth of money
    $('.linha').each(function(){;
    var custo = $(this).find(".custo").val();
        var custoConvertido = parseFloat(custo.replace(",", "."));
        var quantidade = $(this).find(".quantidade").val();
        var total = custoConvertido * quantidade

        //testa se o valor da linha é > 0 para considerar na soma;
        if (total > 0){
            amount_sum += parseFloat(total);
            sum = amount_sum.toFixed(2).toString().replace(/\./g, ',');
            console.log(amount_sum);
            console.log(sum);
        }
    });
    //teste se a soma total for zero
    if(amount_sum == 0)
        sum = "0,00";
    else
        sum = amount_sum.toFixed(2).toString().replace(/\./g, ',');

    $('#valor').html(sum);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.