user537137
user537137

Reputation: 614

Get subtotal of inputs and then add

I have this fiddle that adds the total of the inputs perfectly and changes as the inputs change. But I also need it to take into account the quantity of each item.

So the current total is $105 but it should be it should be $235, taking into account the Qty of 3 items that are $65.

Checking out the fiddle will show you what I mean.

http://jsfiddle.net/4n7k012b/1/

        $(document).ready(function () {

            var sum = 0;
                //iterate through each textboxes and add the values
                $("input[class='cmb_text_money']").each(function () {
                    //add only if the value is number
                    if (!isNaN(this.value) && this.value.length != 0) {
                        sum += parseFloat(this.value);
                    }

                });

            $("#sum").html(sum.toFixed(2));

            $(document).on('keyup',"input[class='cmb_text_money']", function () {
                var sum = 0;
                //iterate through each textboxes and add the values
                $("input[class='cmb_text_money']").each(function () {
                    //add only if the value is number
                    if (!isNaN(this.value) && this.value.length != 0) {
                        sum += parseFloat(this.value);
                    }

                });

            $("#sum").html(sum.toFixed(2));
            console.log(sum);

            });
        }); 

Upvotes: 0

Views: 69

Answers (1)

adeneo
adeneo

Reputation: 318302

Here's one way to do that, traversing up to the quantity and then multiplying with the price, storing each sum in an array that is then summed up at the end

$(document).on('keyup', 'input.cmb_text_money, input.cmb_text_small', function () {
    var sum = $.map($('input.cmb_text_money'), function(item) {
        return $(item).closest('tr').prev('tr').find('input').val() * item.value;
    }).reduce(function(a, b) { 
        return a + b; 
    }, 0);

    $("#sum").html(sum.toFixed(2));
});

FIDDLE

Upvotes: 1

Related Questions