[Answered ]-Twitter typeahead.js autocomplete remote not working

2πŸ‘

βœ…

I can see two problems:

1) Your script declaration is missing a type attribute:

<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.js"></script>
<script type='text/javascript' src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

add β€œtype=’text/javascript'” to the script declarations for jquery and bootstrap.

A more modern way of declaring your script tags can be found here.

2) To initialise Typeahead you need to place the code into your jQuery ready method i.e.

$(function(){
 var stocks = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.name);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 5,
    remote: {
        url: "/search/autocomplete/",
        replace: function(url, query) {
            return url + "?q=" + query;
        },
        filter: function(stocks) {
            return $.map(stocks, function(data) {
                return {
                    tokens: data.tokens,
                    symbol: data.symbol,
                    name: data.name
                }
            });
        }
    }
});
stocks.initialize();
$('.typeahead').typeahead(null, {
        name: 'stocks',
        displayKey: 'name',
        minLength: 1, // send AJAX request only after user type in at least X characters
        source: stocks.ttAdapter()
    }); 
});

As it is currently the typeahead code wont get loaded.

πŸ‘€Ben Smith

Leave a comment