Search code examples
javascriptjsontwitter-bootstrapbootstrap-typeahead

Bootstrap typeahead with json object instead of string


I got typeahead working by handing bootstrap a simple flat json array of strings like ["php","php4","php5"]. All of the standard functions do what I want in this case.

However I'd like to give the data in a format like the following:

[
    {
        "name":"php",
        "count":123
    },
    {
        "name":"php4",
        "count":3532
    },
    {
        "name":"php5",
        "count":999
    }
]

And with that I'd like to format my typeahead to use both name and count. Perhaps produce something that looks like php5 (999) and when you choose the typeahead it will just output php5. I figured it would be easy to do if I just override all of the functions.

$('.input-classname').typeahead({
        source: function (query, process) {
            // Source here
        },
        updater: function (item) { // What gets sent to the input box
            return item.name;
        },
        highlighter: function(item) {
            return item.name + " (" + item.count + ")";
        },
        matcher: function (item) {
            // Do the matching
        },
        sorter: function (items) {
            // Do the sorting
        }
    });

This works fine but I'd like to use the base versions of highlighter, matcher, and sorter to do the grunt work. And I'd just pass in item.name instead of the item. However I don't know how to get at the base versions of these functions. Is there some way to do this?


Solution

  • Sure, just call/apply the methods on the Typeahead prototype, e.g.

    var Typeahead = $.fn.typeahead.Constructor;
    
    $(".input-classname").typeahead({
      // ...
      matcher: function (item) {
        // do something with item
        return Typeahead.prototype.matcher.call(this, item);
      },
    
      sorter: function (items) {
        // alternatively
        // do something with items
        return this.constructor.prototype.sorter.call(this, items);
      }
    });