Reputation: 265
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
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
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