How to calculate Total via Javascript

Asked

Viewed 723 times

3

To show the items of a sale I use a Json to show 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 (Value * Quantity) My question is how to add the TOTAL of all items, to inform the sale value.

  • 1

    What gives console.log(typeof itensVenda[i].PrecoUnitario, typeof itensVenda[i].Quantidade)?

  • 1

    I don’t get it. You’re already adding up the total here: total = (itensVenda[i].PrecoUnitario * itensVenda[i].Quantidade) + total;.

  • How do I pass this value to an HTML element?

  • 1

    To move to html would be $("#id_element_html"). html(value); -> $("#total_html"). html(total); . In your html code, to display you use : <span id="total_html"></span>

1 answer

2


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

var total = 0;

You can also add up the values using the operator +=

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

Functional example: Jsfiddle

  • 1

    With your example I managed to do, thank you!

Browser other questions tagged

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