Reputation: 4508
loopVar=1;
alert('#imgAvatar'+parseInt(loopVar)+1);
gives me #imgAvatar11
While
alert(parseInt(loopVar)+1);
gives me 2
How can I get #imgAvatar2 ?
Upvotes: 1
Views: 377
Reputation: 2242
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.
Upvotes: 2
Reputation: 318252
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
Upvotes: 3
Reputation: 18598
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) );
Upvotes: 1
Reputation: 16587
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/
Upvotes: 5