0

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!

rails_has_elegance
  • 1,590
  • 4
  • 21
  • 37
  • 1
    you should use if ($('#tokens').length) if you want to check existence of $('#tokens') element. – Anoop Oct 03 '12 at 21:29
  • so you want this ran on dom ready? How does the select_menu div change it's value? – wirey00 Oct 03 '12 at 21:30
  • is `$("#select_menu")` an `input` element? If not, `val` will not work. – Shmiddty Oct 03 '12 at 21:55
  • thanks everybody! problem already solved, @Shmiddty, yes its an input element. And I indeed needed to change it to .length > 0, I was in coffeescript before (rails app) and this wasn't well translated somehow. (wanted to present the problem in javascript so more people might be able to help) – rails_has_elegance Oct 03 '12 at 22:01

2 Answers2

0

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.

Stuart Nelson
  • 4,202
  • 2
  • 23
  • 26
0

Apart from the length > 0 call I had to make (thanks for pointing that out Stuart Nelson and Shusl!), it turned out that the string interpolation in coffeescript somehow wasn't working as I wanted. The same code translated into javascript did actually work. Coffeescript was being translated into:

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

Now, the working code is, directly written in javascript/jquery ,is:

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

Note these extra parenthesis in

(("/tokens.json?b=" + bparam)

whereas

("/tokens.json?b=" + bparam 

is the working solution.

rails_has_elegance
  • 1,590
  • 4
  • 21
  • 37