Twitter typeahead autocomplete to dynamically added inputs
Asked Answered
H

2

7

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);
    });
Hagiography answered 11/3, 2014 at 9:12 Comment(0)
S
20

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.

Spendable answered 3/4, 2014 at 22:23 Comment(1)
I receive TypeError: $(...).typeahead is not a function when I put $('.typeahead_option_items').typeahead('destroy'); in a function. But outside the function .typeahead is recognized and works. why ?Let
K
0

I have a very simple way to solve it, use the Function instead of Dynamic input. I mean: typeahead="item in calculatedInput($viewValue)"


The root problem about using typeahead="item in $scope.dynamicArrayInput is: When the model change -> ng-change and typeahead fire event synchronize start So while calculatedInput() function doing something for get a dynamic input, the typeahead said model "jump in $scope.dynamicArrayInput then get something like $viewValue RIGHT NOW". And then filter $viewValue in []. When calculatedInput() finish his work, typeahead already found nothing and do not fire event until u change model one more time. So you always filter typeahead in (lastest - 1) dynamic array.

Kwangtung answered 28/3, 2019 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.