Skylineman
Skylineman

Reputation: 576

jQuery selector with sum

I didn't know a good title for my problem, this is why I didn't search.

My problem is the following:

I have a HTML code, for example:

<input type="text" id="product_qty_1" value="12" />
<input type="text" id="product_qty_2" value="21" />
<input type="text" id="product_qty_3" value="45" />

I'd like to make a sum of the values by jQuery, but this need to be automatic, because we can't know how many inputs are there.

I don't know, what to do with the selector input[id*="product_qty_"] to get it working, and make a sum of the values!

Thanks in advance!

Upvotes: 4

Views: 3584

Answers (2)

adeneo
adeneo

Reputation: 318302

var total=0;

$("input[type='text']").each(function() {
    total += parseInt(this.value, 10);
});

Upvotes: 8

Michael Robinson
Michael Robinson

Reputation: 29498

You could use jQuery's each loop:

var sum = 0;
$('input[id*="package_qty_"]').each(function() {
    sum += parseInt(this.value, 10);
});
alert(sum);

Upvotes: 4

Related Questions