Why does this concatenate instead of adding up

后端 未结 3 611
夕颜
夕颜 2020-12-12 05:04

Very very basic question but I\'ve got the following HTML:




        
相关标签:
3条回答
  • 2020-12-12 05:44

    Do I need to use parseInt or something?

    Yes. The .val() method returns a string, so you need to make sure you're operating on numbers instead (since the + operator is overloaded to perform both addition and concatenation depending on context):

    one = parseInt($('#nspcc').val(), 10);
    //etc...
    

    Don't forget the second argument (the radix) to parseInt!

    0 讨论(0)
  • 2020-12-12 05:44

    Do I need to use parseInt or something?

    Exactly. val() will return strings, which will get concatenated and not added up.

    Do note that when using parseInt you should supply the radix parameter (second one) for the correct base - 10 for decimal, otherwise it will assume octal.

    one = parseInt( $('#nspcc').val() , 10);
    
    0 讨论(0)
  • 2020-12-12 06:05

    Short answer, yes. You'll need to parseInt() your .val() values as they're string interpretations of the values, so they'll simply concatenate.

    0 讨论(0)
提交回复
热议问题