Mark
Mark

Reputation: 1872

jQuery - Adding values of multiple inputs together & display in another input

I have some code, that to my mind, should be finding all classes '.stock-input', adding their values together, and displaying that value in the id #pStockQuantity, I can't see why I'm getting the result NaN.

JS:

$('.stock-input').keyup(function() {
    var stockTemp = parseInt(0);
    $('.stock-input').each(function() {
        stockTemp = parseInt(stockTemp) + parseInt($(this).val());
    });
    $('#pStockQuantity').val(stockTemp);
});

Upvotes: 0

Views: 1289

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The problem will come if a textfield has a non numeric value

$('.stock-input').keyup(function () {
    var stockTemp = 0;
    $('.stock-input').each(function () {
        stockTemp += parseInt($(this).val()) || 0;
    });
    $('#pStockQuantity').val(stockTemp);
})

Demo: Fiddle

Upvotes: 2

Related Questions