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..
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 + "]"));
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]);
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