lancey
lancey

Reputation: 377

How do i calculate the sum of all inputs with the same ID in JQuery

They are dynamically created inputs using "append" method and have an id="subtotal1", id="subtotal2" and so on. How do i calculate the sum of all the inputs and display it within a div in JQuery?

Upvotes: 0

Views: 1521

Answers (2)

Balachandran
Balachandran

Reputation: 9637

try

var sum=0;

$("[id^=subtotal]").each(function(){      
 sum=sum+(parseInt(this.value,10));
});

console.log(sum);

DEMO

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Try,

$('button').click(function () {
    $('div').text($.map($('input[id^="input"]'), function (elem, i) {
        return parseInt(elem.value, 10) || 0;
    }).reduce(function (a, b) {
        return a + b;
    }, 0));
});

DEMO

Upvotes: 1

Related Questions