Search code examples
autocompletetwitter-bootstrap-3typeahead.jsbootstrap-typeahead

twitter bootstrap 3.0 typeahead ajax example


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.


Solution

  • 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.