redviper2100
redviper2100

Reputation: 265

Append a variable value to the id in jquery

How can I append a variable value to the end of the id? I have this code:

n = 2;
$("#input_color").spectrum({
             preferredFormat: "rgb",
             color: "#f00"
         });

and I want to look like this:

n = 2;
$("#input_color2").spectrum({
             preferredFormat: "rgb",
             color: "#f00"
         });

Is there any way to merge it like this?

n=2;
$("#input_color + 'n'").spectrum({
             preferredFormat: "rgb",
             color: "#f00"
         });

Upvotes: 1

Views: 1094

Answers (2)

Amit
Amit

Reputation: 46361

Concatenating a value with a string in JavaScript is quite simple, you use the plus sign (+), but you need to do that outside of the string:

n=2;
$("#input_color" + n).spectrum({
    preferredFormat: "rgb",
    color: "#f00"
});

Upvotes: 3

user1090751
user1090751

Reputation: 336

Take n variable out of '". If you place variable n inside quots it becomes string n instead of being variable n having value 2.

Final working code:

n=2;
$("#input_color" + n).spectrum({
    preferredFormat: "rgb",
    color: "#f00"
});

Upvotes: 4

Related Questions