Haroldas
Haroldas

Reputation: 1010

How to count total sum jquery?

I have table with the price of quantity. I need count total sum if i write quantity in input and select the colors from dropdown and select product with the price. Firstly i need array of quantity and colors price. Second, check number is in table quantity column. Input must be smallest 30. For ex.: if number 299 - quantity is 200, if 4300 - quantity is 3000 and etc. to smaller. There is my table and jquery:

var total = $("#Total").val();
var table = Array();
$("table.quantity tr td:nth-child(1)").each(function (i, v) {
    table[i] = $(this).text();
});

console.log(table);
$('#Quantity').on("input", function () {
    var quantity = this.value;
    var count = 0;

    if (quantity >= 30) {
        $.each(table, function (i, value) {
            if (quantity >= parseInt(value)) {
                count = value;
            };
        });
        console.log(count);
    }
});
$('#select-model').on('change', function(){
    var price = $('option:selected', this).data('price');
    if (total == '') {
        total = 1;
    }
    $("#Total").val(price * total);
});

i think array must be like:

Array 
( 
    [30] => Array 
        ( 
            [1] => 1.4 
            [2] => 1.7
...
            [8] => 
        ) 
    [50] => Array 
        ( 
            [1] => 1.1 
            [2] => 1.3
...
            [8] => 2.4
        ) 
...
    [5000] => Array 
        ( 
            [1] => 0.3 
            [2] => 0.35
...
            [8] => 1
        ) 
)

there is my code: http://jsfiddle.net/Dewilas/cz69vL8u/

total result to be:

for ex.: 6.59 * 5000 * 0.3 (product1 * quantity 5000 * color 1)

Upvotes: 1

Views: 1602

Answers (1)

Domain
Domain

Reputation: 11808

I think, you want multiplication and not sum -

See if the following helps you -

You can add a common class selector to all of your inputs and then do the calculation. I have assumed it to be 'myinput'.

$('.myinput').on('change', function () {

        var total = 1;
        var input_val;

        $('.myinput').each(function(){

            if($(this).attr("id") == "select-model"){
                input_val = $('option:selected', this).data('price');
            }
            else{
                input_val =  $(this).val();
            }

            if (input_val == '' || input_val == 0) {
                input_val = 1;
            }

           total = total * input_val;

        });

        $("#Total").val(total);
    });

Note: I have considered the quantity as 1 by default so that value for other inputs can be seen by default in the total box, so you can change that if you want.

JS Fiddle: http://jsfiddle.net/cz69vL8u/22/

Upvotes: 1

Related Questions