1
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
asked Sep 7, 2013 at 18:51
2
  • 1
    You're adding strings, convert them to numbers and you'll be fine ;) Commented Sep 7, 2013 at 18:54
  • Looks like you're concatenating strings instead of making additions. Commented Sep 7, 2013 at 18:54

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try with

totalvalue += parseInt(document.getElementById("rcv_amount_"+x).value, 10);
answered Sep 7, 2013 at 18:54

5 Comments

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)
As far as I know, that parameters is optional, and 10 by default.
No, by default it's guessed from the string. And while octal (leading zero) is gone in most browsers, it still handles 0x... as hex
Couln't agree more. Always use JSLint to prevent such situations. They can be a pain to find.
@Portnoy it's optional, but the default value is zero, meaning "figure it out from the string".

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.