Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Treat a string like a variable name

Tags:

jquery

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!

like image 391
Hung Tran Avatar asked Jun 08 '11 17:06

Hung Tran


1 Answers

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.

like image 86
Fosco Avatar answered Sep 23 '22 15:09

Fosco