bassjobsen / Bootstrap-3-Typeahead

The Typeahead plugin from Twitter's Bootstrap 2 ready to use with Bootstrap 3 and Bootstrap 4
1.68k stars 1.33k forks source link

It is possible to show autosuggestions list after user click in show input? #376

Open jakubstankowski opened 5 years ago

jakubstankowski commented 5 years ago

Hi!

I have question - it is possible to show suggestions list after user click in input ? I mean something like google, show list only click in input

thanks for answer!

salt-istanbul commented 5 years ago

Hi, I found a pretty simple solution. You may show predefined suggestions on focus when query is blank.

$('.typeahead').typeahead({
            source: function (query, process) {
                if(query == ""){
                                //query is blank: show predefined suggestions
                                return this.process([{"id":172,"name":"default item 01","url":"http://www.test.com"},{"id":73,"name":"default item 02","url":"http://www.test2.com"}]);
                }else{
                                 //query is not blank: make an ajax call
                     return $.post("http://example.com/query", { query: query } , function (data) {
                          data = $.parseJSON(data);
                          return process(data);
                    });                 
                }
            },
            fitToElement : true,
            minLength : 2,
            theme : "bootstrap4",
            afterSelect: function(args){
                 window.location.href = args.url;
            },
        }).on("focus", function(e){
            if($(this).val() == ""){
                var typeahead = $(this).data("typeahead");
                    typeahead.query="";
                    typeahead.source("");
            }
});