tags:

views:

30

answers:

2

I am using the jQuery Tokenizing autocomplete plugin (http://github.com/loopj/jQuery-Tokenizing-Autocomplete-Plugin) and I create new input types on the client side using the $('selector').after('html'); method. When I do this, the newly created element does not use the plugin.

The initial input is tokenized like this

$('.recipe_ingredient').tokenInput('/ingredients/index.json', {
  hintText: 'Type in an ingredient like Tuna, Chicken...',
  tokenLimit: 1,
  onAdded: ingredient_added,
  onRemoved: ingredient_removed,
});

Any new input types matching the selector does not get tokenized, any ideas? I am getting lost in the syntax.

EDIT

I ended up doing something like this

clickedContainer.after('html');

 $('#total-i-forms').attr('value', count);

 var ri = clickedContainer.next().find('.recipe_ingredient');

 ri.tokenInput('/ingredients/index.json', {
  hintText: 'Type in an ingredient like Tuna, Chicken...',
  tokenLimit: 1,
  onAdded: ingredient_added,
  onRemoved: ingredient_removed,
 });

Is this method preferred over live query?

A: 

You can use the .livequery() plugin for this:

$('.recipe_ingredient').liveQuery(function() {
  $(this).tokenInput('/ingredients/index.json', {
    hintText: 'Type in an ingredient like Tuna, Chicken...',
    tokenLimit: 1,
    onAdded: ingredient_added,
    onRemoved: ingredient_removed,
  });
});

It actively looks for new elements added to the DOM that match the selector and runs the callback function on them. Think .each(), but it continues to run for new elements that are added.

Nick Craver
A: 

You'll need to bind it to any new inputs. The point at which the plugin method is run binds it only to those elements that exist in the DOM at that point.

Russ Cam
Unfortunately you can't use `.delegate()` or `.live()` for plugins like this...they're strictly for event handling, and are activated by bubbling, not the addition of elements :)
Nick Craver
Yes, I added the same code after $('selector').after('html'); and it is working fine. Is this method preferred over the livequery plugin?
iHeartDucks
@iHeartDucks: If you put the code after, it'll be running the plugin *again* for the previously run elements, so the more elements you have, the worse it gets...you're better off running it specifically on the created elements or using `.livequery()`.
Nick Craver
Good call Nick, I was thinking about custom events when I started to answer :)
Russ Cam