简体   繁体   中英

Typeahead doesn't work at all

Using twitter typeahead: https://twitter.github.io/typeahead.js

I'm trying to initialize multiple typeaheads via a data-typeahead attribute which represents part of the URL I want to use as the source.

I need to be able to call this after dynamic new [data-typeahead] elements are added to the page.

My code is not working at all. It doesn't even work on [data-typeahead] elements which are already on the page.

$('[data-typeahead]').typeahead({
    source: function (query, process) {
        $.get(this.$element.data('typeahead')+'/'+query, function (data) {
            alert(data);
            process(data);
        });
    },
    items: 10
});

Any help would be greatly appreciated.

Had to create a new function containing an each loop and call it when the page loads, as well as any time a new typeahead element is added to the DOM.

The each loop destroys all existing typeaheads and then re-initializes them.

I spent hours on this and this is the only solution that worked.

function initialize_typeaheads () {
    $('[data-typeahead]').each(function () {
        var element = $(this);

        element.typeahead('destroy');

        var results = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: element.data('typeahead')+'/'+'%QUERY',
                wildcard: '%QUERY'
            }
        });

        element.typeahead(null, {
            source: results,
            limit: 10
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM