How to calculate Total via JavaScript

3

To show the items in a sale I use a Json to display the data using this script.

<script>
$(document).ready(function () {      
    var CodigoVenda = @ViewBag.CodigoVenda;
    $.ajax({
        type: "GET",
        url: "/Venda/GetDadosItensVenda?Codigo="+ CodigoVenda,
        success: function (itensVenda) {

            if (itensVenda != null) {
                var total;

                $('#tbody').children().remove();

                $(itensVenda).each(function (i) {

                    total = (itensVenda[i].PrecoUnitario * itensVenda[i].Quantidade) + total;

                    var tbody = $('#tbody');
                    var tr = "<tr>";
                    tr +=
                    tr += "<td>" + itensVenda[i].Codigo;
                    tr += "<td>" + itensVenda[i].CodigoProduto;
                    tr += "<td>" + itensVenda[i].Quantidade;
                    tr += "<td>" + itensVenda[i].PrecoUnitario;
                    tr += "<td>" + (itensVenda[i].PrecoUnitario * itensVenda[i].Quantidade);
                    tbody.append(tr);
                });
            }
        }
    });
});

As we can see, to know the SubTotal I do the (ValorUnitario * Quantity) My question is how to add the TOTAL of all the items to inform the sales value.

    
asked by anonymous 30.11.2015 / 21:04

1 answer

3

Your problem is that you did not specify the initial value of the total variable, so when it will try to do it it returns a NaN (not a number), you just assign a value that Your code works:

var total = 0;

You can also add the values using the +=

total += (itensVenda[i].PrecoUnitario * itensVenda[i].Quantidade);

Functional example: JSFiddle

    
30.11.2015 / 22:08