Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter typeahead autocomplete to dynamically added inputs

I am using Twitter typeahead on my website and it works fine. But when I try to add new input dynamically it doesn't work. What could be the problem?

Thank you for replies.

    var custom = new Bloodhound({
    datumTokenizer: function(d) { return d.tokens; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: 'http://'+window.location.hostname+'/invoice/loadItemOption?query=%QUERY'
    });

    custom.initialize();

    $('.typeahead_option_items').typeahead(null, {
          name: 'item_title[]',
          displayKey: 'invoice_item_option_title',
          source: custom.ttAdapter(),
          hint: (App.isRTL() ? false : true),
    }).on('typeahead:selected', function (obj, value) {
        console.log(value.invoice_item_option_title);
    });
like image 991
user3359391 Avatar asked Mar 11 '14 09:03

user3359391


1 Answers

What I did was I wrapped this into a function

function typeahead_initialize() {
 var custom = new Bloodhound({
    datumTokenizer: function(d) { return d.tokens; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: 'http://'+window.location.hostname+'/invoice/loadItemOption?query=%QUERY'
    });

    custom.initialize();

    $('.typeahead_option_items').typeahead(null, {
          name: 'item_title[]',
          displayKey: 'invoice_item_option_title',
          source: custom.ttAdapter(),
          hint: (App.isRTL() ? false : true),
    }).on('typeahead:selected', function (obj, value) {
        console.log(value.invoice_item_option_title);
    });
}

typeahead_initialize();

and than before adding the dynamic input I run

$('.typeahead_option_items').typeahead('destroy');

and after the element is created

typeahead_initialize();

Works for me, hope this helps.

like image 193
user1049961 Avatar answered Oct 07 '22 21:10

user1049961