Bootstrap 4 Typeahead

Fredmat picture Fredmat · Mar 16, 2018 · Viewed 35k times · Source

I'm using jQuery Bootstrap Typeahead. I get data from my file but typeahead dropdown is not populate/shown.

Here is my JS:

(function() {
    "use strict";

    var $input = $('.typeahead');

    $('.typeahead').typeahead({
        source: function (query, process) {
            return $.getJSON(
                'url-to-file.php',
                { query: query },
                function (data) {
                    console.log(data)
                    return process(data);
                })
        }
    });

})();

console.log() returns a (correct) JSON array:

[ "item1", "item2", ... ]

But I don't know what to do after. Thanks for helping

Answer

Zim picture Zim · Mar 16, 2018

The data source should be...

[{name:"item1","id":"1"},{name:"item2","id":"2"},etc..]

And then use data-provide on an input like this...

   <div class="input-group">
       <input type="text" data-provide="typeahead" class="form-control typeahead border-primary" name="query" id="query" placeholder="search..." autocomplete="off">
   </div>

Working Demo on Codeply


Edit: You can also use a simple string array: https://www.codeply.com/go/knBpcbhlFE