Search code examples
ruby-on-railstwitter-typeahead

nested_form and twitter typeahead


I have implemented nested_form gem and twitter type ahead in my app. But I can not get the typeahead to work on the dynamically added fields.

My line that adds the dynamic lines is <%= ff.link_to_add t("add_author"), :book_authors, :data => { :target => "#authors"} %>

And The JS for the typeahead of the first line is:

$(function(){
  var authors = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('author'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: {
      url: '/load_suggestions?q=%QUERY',
      filter: function(list) {
        return $.map(list, function(author) { return {author: book }; });
      }
    }
  });

  authors.initialize();

  $('#load_suggestions').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
  },
  {
      name: 'authors',
      displayKey: 'author',

      source: authors.ttAdapter()
  });
});

How do I modify the above to work for the dynamically added lines? Thanks


Solution

  • You can listen for click events and activate typeahed after field was added., handling javascript events is given in the README of nested_form gem.

    e.g.

     $(document).on('nested:fieldAdded', function(event){
          // this field was just inserted into your form
          var field = event.field; 
          field.typeahead({
            hint: true,
            highlight: true,
            minLength: 1
          },
          {
             name: 'authors',
             displayKey: 'author',
    
             source: authors.ttAdapter()
         });
    });