Search code examples
javascriptjqueryjquery-tokeninputstring-interpolation

jquery string interpolation causing problems


I'm using the jquery tokeninput plugin, and I want the json token input data to be dependent upon a value that can be found somewhere in the form. My code looks like this:

jQuery(function() {
  var bparam;
  if ($('#tokens')) {
    bparam = $('#select_menu').val();
    return $('#tokens').tokenInput(("/tokens.json?b=" + bparam)({
      theme: 'facebook',
    }));
  }
});

So the plugin should make a request such as /tokens.json?b=124 if that value from the select_menu div was 124.

Somehow this just doesn't work and I don't know why. I'm still kindof a javascript newbie. Any help appreciated!


Solution

  • if ($('#tokens')) will return an empty array ([]), so no matter what that will always evaluate to true. I'm guessing you want if ($('#tokens').length). If there is an item in the array it will evaluate to true, if it's empty it evaluates to false.

    What's tripping you up is when the variable is being set. bparam is being set on page load. I would bind it to be set when whatever is triggering the event occurs.