Search code examples
javascriptjquerythickbox

Concatenated variable as selector not working (Javascript/Jquery)


I'm puzzled & pretty unexperienced with jQuery. I'm trying to pass back a value from a thickbox window into an input element on the parent page. To determine the right input box I'm trying to concatenate two values, one of which I successfully grab from the thickbox window and the other value is a piece of text, like example below.

grab_flavor = $('#flavor').val(); //contains 'apple'
alert(grab_flavor); // returns 'apple'
juice = "#" + grab_flavor + "juice";
alert(juice); // returns '#applejuice'
$(juice , top.document).val("favorited"); //doesn't seem to work...
flavor = "#apple";
juice = flavor + "juice";
$(juice , top.document).val("favorited"); // works

I can't seem to figure out why the first concatenation isn't working, even though it returns the right value when I display it with an alert, instead nothing happens.

I've tried a number of different ways to concatenate, but they all fail when I try to include 'grabflavor'...advice much appreciated!

update: working on a better live example...

update 2 (final): figured it out...syntax was valid after all, nothing wrong with the concatenation, I just overlooked a small detail because I was dealing with very long selectors that looked the same...next time I will take a longer break so I can benefit from fresh eyes. Stubbornly obsessing to understand a problem doesn't always work so well. Thank you commenters for posting and pointing out jsfiddle and jsbin, two incredibly useful finds!


Solution

  • Unless it's another typo during transcription, the problem is here:

    juice = "#" + grabflavor + "juice";
    

    You're missing the underscore in grab_flavor. Correct that, and it works (live copy).