Add and remove fields dynamically with sum and multiplication of values

1

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

See the Fiddle below for a better understanding.

JsFiddle: link

This structure is almost 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 to add the value of all the lines.

    
asked by anonymous 24.06.2016 / 22:36

1 answer

2

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

You should validate after the loop that made the sum, and test if amount_sum is zero to zero the total. And test the total only to confirm whether it will be considered in the sum total.

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);
}
    
24.06.2016 / 22:55