Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

javascript - Why does this concatenate instead of adding up

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

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

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...