twitter bootstrap 3.0 typeahead ajax example

Pascal Klein picture Pascal Klein · Apr 10, 2014 · Viewed 100.9k times · Source

There are a lot of typeahead ajax examples out there for bootstrap 2, for example this here twitter bootstrap typeahead ajax example.

However I am using bootstrap 3 and I could not find a complete example, instead there are just a bunch of incomplete information snippets with links to other websites, for example this here Where is the typeahead JavaScript module in Bootstrap 3 RC 1?

Could someone please post a fully working example on how to use typeahead with bootstrap 3, if you load the data from the server via ajax, every time the user changes the input.

Answer

Michael picture Michael · Sep 11, 2014

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.