This is my shortened script:
var string1 = "This is string 1";
var string2 = "This is string 2";
function test() {
var selectedOption = $("select#myoptions option:selected").attr("id");
var str = 'string'+selectedOption;
$("div#result").html(str);
}
$("select#myoptions").change(test);
I have a drop down list, every option has an integer id. When selecting this drop down list, I want jQuery gets the id of the selected option and displays the content of the string variable which has the selected id at the end.
If option with id "1" is selected, "This is string 1" will be displayed, ...
But what I get now is the text "string1" displayed instead of the text "This is string 1".
I need some help. Thanks so much!
You could update your test function to use eval():
function test() {
var selectedOption = $("select#myoptions option:selected").attr("id");
eval('$("div#result").html(string' + selectedOption + ');');
}
Give that a shot.
I provided this as a way of giving you exactly what you asked for, though I really like the answer provided by Rocket which requires a small change on how you store your strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With