user2957967
user2957967

Reputation: 71

Calculate with Jquery

I'm trying to sum the values of my number inputs. I want to get all the input values and sum them.

Here's my HTML:

<input type="number" min="1" max="20" id="number-<?php echo $item_slug; ?>" class="number-label" value="1" />

And my jquery:

function itensSoma2() {
    $('.number-label').each(function() {
        var soma2 = 0;
        soma2 += parseInt($(this).val());
        console.log(soma2);
    });
}

But all i get in my console is alot of number 1!!

Upvotes: 0

Views: 88

Answers (1)

fmsf
fmsf

Reputation: 37177

You need to declare your variable outside the loop:

function itensSoma2() {
    var soma2 = 0;
    $('.number-label').each(function() {
        soma2 += parseInt($(this).val());
        console.log(soma2);
    });
}

Upvotes: 6

Related Questions