7

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

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Fredmat
  • 938
  • 4
  • 14
  • 34

1 Answers1

4

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

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 1
    Actually your example works fine, but it loads the json data directly. My goal is that each time the user press key, a query is done in my database searching for the query and "then" return the json data. I'm ok with that but after I don't know how to inject/populate the dropdown list. – Fredmat Mar 17 '18 at 13:04
  • That would basically work the same as explained here: https://stackoverflow.com/questions/18710325/twitter-bootstrap-typeahead-custom-keypress-enter-function – Carol Skelly Mar 17 '18 at 23:52
  • booth codeply examples doesnt work for me in FireFox (65.0.5) but works in Chrome – Grain Aug 24 '19 at 08:53
  • The links work for me, and besides the relevant code is in the answer too. Why did you downvote this? @SergeyRomanov – Carol Skelly Sep 10 '19 at 14:17
  • Because all links ave me 404 at that time like example is not there anymore. Now all works fine. I wanted to upvote but it does not let me until a post is edited. Sorry. Most probably that was so a problem with a codeply. Because 404 error was not a browser but their. Styles as codeply not found repo. – Sergey Romanov Sep 11 '19 at 13:53