Zamoyski
Zamoyski

Reputation: 55

Count multiple values with jquery

I am trying to create counting function with jquery.

I have multiple sets of inputs with numbers determined, something like:

<input class="price" type="hidden" name="price" value="4">
<input class="count" type="text" name="count" maxlength="4">

I want to create script that will count all inputs, eg.

 (price * count) + (price * count) etc..

So far i came up with this script, which multiplies and displays only one input

$('.count').blur(function() {
    var amount = parseFloat($(this).val());
    var price = $(this).closest('tr').find('.price');
    var result = parseFloat((price).val());
    var money = (amount * result)
    $('.money').text(money);
});

Upvotes: 1

Views: 1599

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use a loop inside your blur handler like

var $counts = $('.count').blur(function () {
    var money = 0;
    $counts.each(function () {
        money += (+this.value * $(this).closest('tr').find('.price').val()) || 0
    });

    $('.money').text(money);
});

Demo: Fiddle

Upvotes: 1

Related Questions