Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

<input type="text" id="nspcc" value="0" onkeyup="doTotal();" />
<input type="text" id="barnados" value="0" onkeyup="doTotal();" />
<input type="text" id="savethechildren" value="0" onkeyup="doTotal();" />
<input type="text" id="childresnsociety" value="0" onkeyup="doTotal();" />
<input type="text" id="childreninneed" value="0" onkeyup="doTotal();" />
<input type="text" id="total" disabled="disabled"  />

And the following jQuery:

function doTotal() {
  var one,two,three,four,five,total;
  one = $('#nspcc').val();
  two = $('#barnados').val();
  three = $('#savethechildren').val();
  four = $('#childresnsociety').val();
  five = $('#childreninneed').val();
  total = one+two+three+four+five;
  $('#total').val(total);
}

doTotal();

I'm probably doing something daft but why does total concatenate instead of adding the values? Do I need to use parseInt or something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...