1

I have multiple text boxes with a class name .paymentamount.i want to add all values of text boxes of the same class but i am getting error nan.Code is this

function paymentData()
{
    $('.paymentamount').keyup(function(){
        var amountSum=0;
        $('.paymentamount').each(function(){
            amountSum+=parseInt(this.value);
        //console.log(this.value);
        });
        console.log(amountSum);

        });
}
1
  • suggest modifying amountSum+=parseInt(this.value); as amountSum+=parseInt($(this).val()); Commented May 15, 2012 at 8:07

5 Answers 5

2
   1. $.trim($(this).val())
   2. make use of $(this).val()
   3. check before adding var match = /^[0-9]$/.test(value); 

Final code for you after this modification to your code

 $('.paymentamount').each(function(){
           var value = $.trim($(this).val()); 
           var match = /^[0-9]$/.test(value); 
           if(match)
             amountSum+=parseInt(value);
         //console.log(this.value);
         });
Sign up to request clarification or add additional context in comments.

Comments

1

Hiya Demo http://jsfiddle.net/MaK2k/1/ or using $.isNumeric http://jsfiddle.net/AKnvr/

**Code**


$('.paymentamount').keyup(function(){
   var amountSum=0;
    $('.paymentamount').each(function(){
        if (this.value != "")
           amountSum+=parseInt(this.value);

    });

    $(".paymentamountlable").text(amountSum);


    });

1 Comment

No probs, @Hira - Glad it helped you can use; extra .isNumeric and isNan if you want to make sure that it only sum up the numeric values! :) Another demo here: jsfiddle.net/AKnvr
1
function paymentData()
{
    $('.paymentamount').keyup(function(){
        var amountSum=0;
        $('.paymentamount').each(function(){
            amountSum+=parseFloat($.trim($(this).val()));

        });
        console.log(amountSum);

        });
}

Comments

0
$('.paymentamount').keyup(function(){
    var amountSum=0;
    $('.paymentamount').each(function(){
        if(parseInt(this.value) > 0)
        {
        amountSum = parseInt(this.value) + parseInt(amountSum);
        }
    }); 

 console.log(amountSum);
});



Try this

Comments

-1

You should try:

amountSum+=parseInt($(this).val());

1 Comment

-1 because parseInt() can return NaN if the value is not numeric, and also because you missed the radix argument for parseInt(). This argument is optional, but should be specified, because otherwise it can default to octal, which can give some unexpected results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.