6

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!

Hung Tran
  • 790
  • 2
  • 8
  • 24

5 Answers5

6

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.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
Fosco
  • 38,138
  • 7
  • 87
  • 101
4

So, I'm surprised nobody added this answer, which directly answers the OP's question. I agree that other approaches are better, but you can certainly solve his problem in the way he asked by doing this:

var str = 'string'+selectedOption;
var foundString = window[str];
JSager
  • 1,420
  • 9
  • 18
3

Any reason you can't do?

function test() {
    var selectedOption = $("select#myoptions option:selected").attr("id");
    var str = 'This is string ' + selectedOption;
    $("div#result").html(str);  
}
$("select#myoptions").change(test);

Actually, I imagine you have different strings than shown, try:

var stringArray = ['this is string 1', 'this is string 2'];
function test() {
    var selectedOption = $("select#myoptions option:selected").attr("id");
    var str = stringArray[selectedOption -1];
    $("div#result").html(str);  
}
$("select#myoptions").change(test);

You cannot dynamically use variables like you mentioned, your best bet is to get an array and pull the items out by index.

Jeremy B.
  • 9,168
  • 3
  • 45
  • 57
3

You can use an object to store these values, and then get them by their key.

var strings = {
  string1: 'This is string 1',
  string2: 'This is string 2'
};

function test() {
    var selectedOption = $("select#myoptions option:selected").attr("id");
    var str = 'string'+selectedOption;
    $("div#result").html(strings[str]);  
}
$("select#myoptions").change(test);

Or, you could leave the strings the way you had them, and access them via the window object, if they are in the global scope.

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(window[str]);  
}
$("select#myoptions").change(test);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    Better then using eval because eval is dangerous – Bernardo Mendes Jun 08 '11 at 17:26
  • @Bernardo I like this option as well, but I must say that calling eval 'dangerous' is pretty silly. Now that every browser has dev tools and javascript consoles, any visitor can execute whatever javascript code they like... There's nothing inherently dangerous about eval. To back up my claim, see this highly rated answer: http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea/87260#87260 – Fosco Jun 08 '11 at 17:28
  • @Fosco eval is dangerous and its not silly, eval can lead to javascript injection. If string1 and string2 are entered by any client you can have malicious and unwanted code into a string. As i dont know if string1/string2 will be entered by the client or not its safer to point a solution that doesnt include eval on it. – Bernardo Mendes Jun 08 '11 at 17:32
  • @Bernardo: The values are from a dropdown, which can be changed by the user. So, yeah `eval` can be dangerous here. – gen_Eric Jun 08 '11 at 17:33
  • 3
    @Bernardo @Rocket Absolutely ridiculous claims you are both making. How would it be dangerous? Do you believe Javascript consoles are dangerous? I've provided well supported backup for using eval(), I think you should provide some evidence for it being more 'dangerous' than opening a javascript console and hacking away in any browser. – Fosco Jun 08 '11 at 17:37
  • @Fosco: I guess `eval` isn't any more dangerous than opening a JS console yourself. `eval` is slower, though. – gen_Eric Jun 08 '11 at 17:42
  • 2
    "Javascript injection"? I "inject Javascript" into pages on a [regular basis](http://userscripts.org/) – Michael Mrozek Jun 08 '11 at 17:43
  • @Fosco: It just seems that people here are always like "OMG EVAL IS EVIL", so, I guess it kinds sticks. – gen_Eric Jun 08 '11 at 17:47
  • 1
    @Fosco You're right that `eval`'s not dangerous. There's no reason the site owner couldn't just use malicious code on his own, or the user couldn't just open up the browser console and type in his own insidious thoughts. The better argument against `eval` is that there are usually methods that are some combination of quicker, easier-to-debug and less volatile out there. The best uses I've seen for `eval` is for code interpreters built on top of JS, use in debugging (i.e. comparing how something should work to an eval'ed statement), etc. For simple lookup functions, though, arrays work nicely. – brymck Jun 08 '11 at 17:50
  • @Rocket fight the power man, think for yourself. There's a lot of things that people consider 'bad practice' for no good reason, or a reason which is no longer valid. I like your answer better anyway, but not because of group-think nonsense about eval. :) – Fosco Jun 08 '11 at 17:51
  • @Fosco pretend that you have a website and there you have a function delete that calls an ajax page that delete the current user. ok... Now pretend that you has anywhere on the site that users can submit 'foos' and you eval 'foos', if someone send a 'delete()' as foo and you eval('delete()') you will be deleting all the current users accounts of everyone that access the page where you eval(foos), now tell me, isnt it dangerous? @Michael: this is a malicious javascript injection. – Bernardo Mendes Jun 08 '11 at 18:00
  • @Fosco: Damn the man, save the empire! (+1 to whoever gets this reference) – gen_Eric Jun 08 '11 at 18:00
  • @Bernardo: So what happens if I enter `javascript:delete()` into the address bar, or if I open my JS console and type `delete()`. – gen_Eric Jun 08 '11 at 18:01
  • @Rocket come on man, if you do that you will be deleting YOUR account, if you eval things that OTHERs users send to your website you will delete everyone that access the page where you eval that thing from others users because it will be eval'ed in every client. My english is very bad but i think you can understand it now – Bernardo Mendes Jun 08 '11 at 18:06
  • @Bernardo Thank you for your example. That would be a terribly designed system and the fault of the designer, not of eval. As Rocket mentioned, you would not need eval() to trigger that stupid ability. You can *never* trust the *client*, whether it be a web browser or a front-end app, you must always validate your actions and input. – Fosco Jun 08 '11 at 18:06
  • @Bernardo Totally get your point, but in your example it sounds like the real danger would be in having a server-side method that allows deleting all users without verification. Never trust users, or user input. – Yuck Jun 08 '11 at 18:07
  • @Bernardo I wish you would realize that eval is not dangerous in the slightest... It's kind of sad that this is still going and you've provided not one piece of evidence to the contrary. Your fictitious example does not work, as the unvalidated magical delete() function is the real danger to be avoided. – Fosco Jun 08 '11 at 18:10
  • @Yuck no.. My example is silly, but take for example facebook.com, they have many functions that send messages to others users, so you would be able to send messages to all the friendlist of every user that access the page where the malicious code is eval'ed. @Fosco, as i said i would prefer this answer because the question has just a example and i dont have a clue if string1/string2 would be entered by any user or not. Eval is powerful and is dangerous, but we have to take care with it. – Bernardo Mendes Jun 08 '11 at 18:10
  • @Bernardo At no point has anyone advocated using eval site-wide based on the user input of others. That would be the danger and a terrible idea, not eval itself. – Fosco Jun 08 '11 at 18:11
  • I did not made myself clear on the first comment, but my second comment i said that i would prefer this answer because i wouldnt knew if string1/string2 would be a user input or not. That's it. – Bernardo Mendes Jun 08 '11 at 18:13
2

No particular reason why it has to be harder than an array, right?

var strs = [
  "This is string 1", // Note, this is strs[0], not strs[1]
  "This is string 2"
];

function test() {
    var selectedOption = $("select#myoptions option:selected").attr("id");
    $("div#result").html(strs[selectedOption]);  
}
$("select#myoptions").change(test);

If you really needed to you could use a hash, like

var strs = {
  dog: "This is string 1",
  cat: "This is string 2"
};

but in any case, 99% of the time when people are trying to look up one variable using one unchanging value (i.e. the name of an array) and one variable (i.e. a key), they want to use something simpler like an array or hash.

brymck
  • 7,555
  • 28
  • 31