Ian Price
Ian Price

Reputation: 7616

Bootstrap-Ajax-Typeahead not showing results when query not in displayField

I have a Bootstrap-Ajax-Typeahead implementation on a Django application that searches pages in our system. I get pages that match a search result based on a query via AJAX and the user can click on the typeahead suggestion and go to the page in question.

However, if the query string is not part of the displayField (title) then the suggestion does NOT show up, though I can see it returned via my search mechanism.

For example, if I search for "motion picture" I have a JSON object return via my search such as:

{
     title: "Movies",
     url: "/movies/",
     description: "Find a motion picture in your area"
}

I want to still show results to the user when a match is found in the description attribute but Typeahead will only show when there's a matching hint.

How can I show search results where the query is not in the displayField?

Note: I am using typeahead-bootstrap w/ Bv3.

$(document).ready(function ($) {
    var JSONSearchURL = "/search/";
    var searchBox = $('#search-form');
    searchBox.typeahead({
        onSelect: function (item) {
            window.location = item.value;
        },
        ajax: {
            url: JSONSearchURL,
            timeout: 800,
            displayField: "title",
            valueField: "url",
            method: "get",
            dataType: "JSON",
            preDispatch: function (query) {
                return {
                    q: query
                }
            },
            preProcess: function (data) {
                return data;
            }
        }
    });
});

Upvotes: 0

Views: 755

Answers (1)

gurch101
gurch101

Reputation: 2064

By default, bootstrap-ajax-typeahead uses the displayField to search for matches. If you want to override this behaviour and also search another field, you need to override the grepper event. Something like this should work (untested):

grepper: function(data){
    var that = this;
    if(data && data.length){
        items = $.grep(data, function(item){
            return that.matcher(item['description']);
        });
        return items;
    }
    return null;
}

See the default implementation of grepper here: https://github.com/biggora/bootstrap-ajax-typeahead/blob/master/src/bootstrap-typeahead.js#L283

Upvotes: 2

Related Questions