Henry Gunawan
Henry Gunawan

Reputation: 942

Iterate into an array of elements

I found this problem, it looks simple but I can't find any solution for this. I have an array of elements like below:

<input type="text" name="subTotal[]"/>
<input type="text" name="subTotal[]"/>
<input type="text" name="subTotal[]"/>
<input type="text" name="subTotal[]"/>

Using jquery, I'd like to count the total from that four subTotal. The count will be triggered when the value of that subTotal is changed. I tried it like below, but it doesn't work:

var totalPrice = 0;
$('input[name="subTotal"]').each( function( key, value ) {
    totalPrice += value;
    alert(totalPrice);
});

Any solutions for this?

Upvotes: 1

Views: 4930

Answers (2)

palaѕн
palaѕн

Reputation: 73896

Try this:

$('input[name^="subTotal"]').change(function () {
    var totalPrice = 0;
    $('input[name^="subTotal"]').each(function () {
        totalPrice += parseInt(this.value);        
    })
    alert(totalPrice);
});

The count will be triggered when the value of that subTotal is changed. Demo here

Upvotes: 0

Anton
Anton

Reputation: 32581

Try this, by using name^= and parseInt on the value

  var totalPrice = 0;
    $('input[name^="subTotal"]').each( function() {
        totalPrice += parseInt(this.value);
        alert(totalPrice);
    });

Demo here http://jsfiddle.net/gBudm/

Upvotes: 4

Related Questions