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?
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):Don’t forget the second argument (the radix) to
parseInt!