1
loopVar=1;
alert('#imgAvatar'+parseInt(loopVar)+1);

gives me #imgAvatar11

While

alert(parseInt(loopVar)+1);

gives me 2

How can I get #imgAvatar2 ?

1

4 Answers 4

5

Your loopVar is already an integer (notice you haven't put it in quotes, so it is integer). No need to do parseInt.

Use it:

loopVar=1;
alert('#imgAvatar'+(loopVar+1));

FIDDLE: http://jsfiddle.net/15bucsy5/

Sign up to request clarification or add additional context in comments.

2 Comments

Guys I Apologize, my loopVar was char probably.
So then, you can use parseInt on loopVar.
3

It's because you're adding to the string #imgAvatar so the numbers will be converted to strings as well, and it's really read as "#imgAvatar" + "1" + "1".

Use parentheses to create a block where the numbers can be added up before they are added to the string

var loopVar = 1;
alert( '#imgAvatar' + ( (+loopVar) + 1 ) );

Whenever the addition operator is used with a string, all other values will be converted to strings as well

FIDDLE

3 Comments

sorry but not working for me. Only Sadikhasan version worked fine.
@David - It's exactly the same as the rest, but who cares !
Guys I Apologize, my loopVar was char probably.
2

Thats the trouble:

"foo" + 1 + 1 == "foo1"+1 == "foo11";

Thats the answer

alert( '#imgAvatar' + ( parseInt(loopVar) + 1) ) );

P.S. jsfiddle: https://jsfiddle.net/emtLfv9r/

If not worknig - show to us your html.

4 Comments

sorry but not working for me. Only Sadikhasan version worked fine.
it because i added jQuery selector, cos i think, that u wanna select that. nvm, glad for u
Guys I Apologize, my loopVar was char probably.
oh, so in that way - right ans is ('#imgAvatar' + ( parseInt(loopVar)+1) )
1

You need to add parenthesis () for priority to evaluate add loopVar first. If your variable contains numeric value then do not need to apply parseInt function.

loopVar = "1";
alert('#imgAvatar'+(parseInt(loopVar)+1));

OR

loopVar = 1;
alert('#imgAvatar'+ (loopVar+1) );

Demo

Comments

Your Answer

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.