David
David

Reputation: 4508

Adding variable to a number in jquery id name

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

Answers (4)

Legendary
Legendary

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

adeneo
adeneo

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

FIDDLE

Upvotes: 3

Sadikhasan
Sadikhasan

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) );

Demo

Upvotes: 1

mehulmpt
mehulmpt

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

Related Questions