mare
mare

Reputation: 13083

jQuery enumerate dynamic table

I have a HTML form that mimics invoice input form.

This is the way I load invoice items (users select them thru autocomplete list using jQuery):

    $(document).ready(function() {
        $("#Products").focus().autocomplete('<%=Url.Action("GetProducts", "Product") %>', {
            dataType: 'json',
            parse: function(data) {
                var rows = new Array();
                for (var i = 0; i < data.length; i++) {
                    rows[i] = { data: data[i], value: data[i].product_name1, result: data[i].product_name1 };
                }
                return rows;
            },

            formatItem: function(row, i, n) {
                return row.product_PrettyId + ' - ' + row.product_name1 + ' (' + row.product_price + ' €) ';
            },
            width: 900,
            minChars: 0,
            max: 0,
            mustMatch: true
        });

        $("#Products").result(function(event, data, formatted) {
            if (data) {
                $(this).parent().next().find("input").val(data["product_id"]);
                $("#InvoiceItems > tbody").append(
                    "<tr>" +
                    "<td>num</td>" +
                    "<td>" + data["product_PrettyId"] + "</td>" +
                    "<td>" + data["product_name1"] + "</td>" +
                    "<td>" + data["product_price"] + "</td>" +
                    "<td></td>" +
                    "<td>1</td>" +
                    "<td>" + data["product_price"] + "</td>" +
                    "</tr>");
            }
        });

After each invoice item added I need to enumerate the table that I'm building - count the items, multiply price with quantity and sum all the items.

How can I do that?

Upvotes: 0

Views: 859

Answers (1)

Jimmy
Jimmy

Reputation: 9815

You might want to add some classes to specific tds for things like quantity, price, and with the total number of items, each time you add a new one you can update a counter and store it within a hidden field and read from that value

EDIT: wrap .each loop in function

function functionName() {
var itemCounter = 0;
$('#InvoiceItems tr').each(function() {
    itemCounter += 1;
    //this loops through each row in the table
    var quantity = parseFloat($('td.quantity', this).text());
    quantity = isNaN(quantity) ? 1 : quantity;//if a number isn't parsed, replace it with 1
    var price = parseFloat($('td.price', this).text());
    price = isNaN(price) ? 0 : price;
    var total = quantity * price;
    //do something with the total
});
}

you could call this function whenever a new item is added so the totals will always be up to date

Upvotes: 2

Related Questions