Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit: People are getting confused. Think of it as a reflective way to get the contents of var test. Preferrably with a JQuery selector, but I'll take any way one can come up with it..

like image 875
KevinDeus Avatar asked Apr 12 '11 19:04

KevinDeus


2 Answers

This should work for you. You have to use the variable outside the string quotes like this. You could replace the # with a . if you want to use a style selector vs an ID selector.

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

If the field is something like <input name="xxx" .../>, you would have to use something like the following:

var test = "xxx";
alert($("[name=" + test + "]"));
like image 87
Christian Avatar answered Nov 25 '22 12:11

Christian


Not sure what your end target is, but I use the following method a lot when I need one thing 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's href URL into the element specified in it's rel attribute
    return(false); // stop processing the link;
 });
});

</script>

I tell the element what the target of the action will be using the rel attribute...

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

var i=2;

var test='i';
document.write('got ' + window[test]);
like image 33
FatherStorm Avatar answered Nov 25 '22 14:11

FatherStorm