Bootstrap 4 Typeahead
Asked Answered
H

1

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

Hwang answered 16/3, 2018 at 15:29 Comment(0)
D
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

Decker answered 16/3, 2018 at 16:59 Comment(5)
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.Hwang
That would basically work the same as explained here: #18710825Decker
booth codeply examples doesnt work for me in FireFox (65.0.5) but works in ChromeSamba
The links work for me, and besides the relevant code is in the answer too. Why did you downvote this? @SergeyRomanovDecker
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.Schaffer

© 2022 - 2024 — McMap. All rights reserved.