totalvalue = 0;
for (x=1; x<6; x++)
{
totalvalue += document.getElementById("rcv_amount_"+x).value;
}
rcv_amount_1 = 2 rcv_amount_2 = 4 rcv_amount_3 = 6
expected result is 12, but i am getting 0246.
Any help?
bcmcfc
27k30 gold badges115 silver badges183 bronze badges
-
1You're adding strings, convert them to numbers and you'll be fine ;)toniedzwiedz– toniedzwiedz2013年09月07日 18:54:37 +00:00Commented Sep 7, 2013 at 18:54
-
Looks like you're concatenating strings instead of making additions.Ende Neu– Ende Neu2013年09月07日 18:54:41 +00:00Commented Sep 7, 2013 at 18:54
2 Answers 2
You have to convert the .value into a number - initially the .value property of an <input> element is a string, so the += operator results in concatenation, not addition.
To convert a string value into a number you can use parseInt(..., 10) for integers, or parseFloat(...) or just +(...) for non-integers.
answered Sep 7, 2013 at 18:54
Alnitak
341k72 gold badges420 silver badges503 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Try with
totalvalue += parseInt(document.getElementById("rcv_amount_"+x).value, 10);
5 Comments
ThiefMaster
You should always specify the second argument to parseInt, i.e. `parseInt(..., 10) to ensure the value is treated as a decimal number (and not e.g. octal or hex)
makmonty
As far as I know, that parameters is optional, and 10 by default.
ThiefMaster
No, by default it's guessed from the string. And while octal (leading zero) is gone in most browsers, it still handles
0x... as hextoniedzwiedz
Couln't agree more. Always use JSLint to prevent such situations. They can be a pain to find.
Alnitak
@Portnoy it's optional, but the default value is zero, meaning "figure it out from the string".
lang-js