1

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?

zik
  • 3,035
  • 10
  • 41
  • 62

3 Answers3

6

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!

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

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);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

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

Chris Dixon
  • 9,147
  • 5
  • 36
  • 68