JQuery select a variable by passing a text string with its name

I would like to use the jQuery selector to return a variable by passing a text string to the variable name:

ex.

var test = "xxx"; 

I think I can do something like this, but this will not work:

  alert($("#test")); 

Edit: People are starting to get confused. Think of it as a reflexive way to get the contents of a var test. Preferably with a jQuery selector, but I will do my best to come up with this.

+8
jquery
source share
7 answers

This should work for you. You should use a variable outside of string quotes like this. You can replace # with . if you want to use a style selector and an identifier selector.

 var test = "xxx"; alert($("#" + test)); 

If the field looks like <input name="xxx" .../> , you will need to use something like the following:

 var test = "xxx"; alert($("[name=" + test + "]")); 
+11
source share

What you are asking is best done with JavaScript objects, for example:

 var obj = { test: "xxx" }; for(key in obj) { alert(key); // "test" alert(obj.key); // "xxx" } 

You can do something like this, although I really don't see the point:

 var obj = { foo: "xxx" }; for(key in obj) { alert($("#" + key).length); // 1 } <input id="foo"/> 

http://jsfiddle.net/J4hC8/

+2
source share

I don't know what the end goal is, but I often use the following method when I need one to interact with another ...

 <a href='whatever.html' rel='#targetElem' class='loadable'> <script> $(document).ready(function(){ $('.loadable').live('click',function(){ //when a element with the class of loadable is clicked $($(this).attr('rel')).load($(this).attr('href')); //load the contents of it href URL into the element specified in it rel attribute return(false); // stop processing the link; }); }); </script> 

I will tell the element what the purpose of the action is to use the rel attribute ...

to get the variables, try this (the window is a built-in array of global javascript variables ...)

 var i=2; var test='i'; document.write('got ' + window[test]); 
+2
source share

Maybe you need

 alert($("#" + test)); 
0
source share
 var test = "#xxx"; alert($(test)); 

Alternatively you can use:

 var test = "xxx"; alert($("#" + test)); 
0
source share

Not sure, but maybe you're looking for eval .

0
source share

I know this is old, but here is the solution. As igor milla pointed out, you should use eval ().

 var test = "xxx"; alert(eval("test")); 
0
source share

All Articles