Skip to content Skip to sidebar Skip to footer

Bootstrap Typeahead Ajax Result Format - Example

I am using Bootstrap typeahead with an ajax function, and want to know what is the correct Json result format, to return an Id and a descripcion. I need the Id to bind the typeahea

Solution 1:

I try for two days and finally I could it working. Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter.

Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options.

II used Json format, and bound the Id to a hidden html input.

The code:

$('#myTypeahead').typeahead({
    source: function (query, process) {
        return $.ajax({
            url: $('#myTypeahead').data('link'),
            type: 'post',
            data: { query: query },
            dataType: 'json',
            success: function (result) {

                var resultList = result.map(function (item) {
                    var aItem = { id: item.Id, name: item.Name };
                    return JSON.stringify(aItem);
                });

                return process(resultList);

            }
        });
    },

matcher: function (obj) {
        var item = JSON.parse(obj);
        return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
    },

    sorter: function (items) {          
       var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
        while (aItem = items.shift()) {
            var item = JSON.parse(aItem);
            if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
            else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
            else caseInsensitive.push(JSON.stringify(item));
        }

        return beginswith.concat(caseSensitive, caseInsensitive)

    },


    highlighter: function (obj) {
        var item = JSON.parse(obj);
        var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
        return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
            return '<strong>' + match + '</strong>'
        })
    },

    updater: function (obj) {
        var item = JSON.parse(obj);
        $('#IdControl').attr('value', item.id);
        return item.name;
    }
});

Solution 2:

Note: I saw @EralpB`s comment "Is this still the best way to accomplish this task?"

Yes, @Gonzalo solution works, but it seems strange (like crutch,especially after using jQuery-Autocomplete) - it should work "from box".Better is to use this - Bootstrap-3-Typeahead. It supports an array of objects as result: format - [{id: .. ,name:...},...,{id: .. ,name:...}]. Example for OP`s issue:

....
 source: function (query, process) {
    return $.ajax({
        ......
        success: function (result) {            
            var resultList = [];

            $.map(result,function (Id,value) {
                var aItem = { id: Id, name: value};
                resultList.push(aItem);
            });

            return process(resultList);
        }
    });
  },

Post a Comment for "Bootstrap Typeahead Ajax Result Format - Example"