Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead.js 0.10.x: how to show number of results per category

Typeahead.js 0.10 supports templates for header and footer as well as for search results. I would like to be able to get the real number of results/suggestions for each category (i.e ignoring the limit value) and display this in the category name header.

for example -

RESULTS:

  • Category A (24 Results)
    • -A1
    • -A2
    • -A3
  • Category B (167 Results)
    • -B1
    • -B2
    • -B3

My template currently looks something like this:

{
name: 'Applications',
displayKey: 'value',
source: app.ttAdapter(),
extraVars:Handlebars.registerHelper("numResults",function(){
    return (  "HowToGetTheseResults??" );
}),
templates: {
    header:Handlebars.compile([
        '<h3 class="applications"> Applications ({{numResults}}) results  </h3>'
    ].join('')),

    suggestion: Handlebars.compile([
        '<p><b>{{value}}</b> </p>'
    ].join(''))
}

Is there an easy way to get type-ahead to return me the number of results/suggestions? I'm sure the typeahead object (or the bloodhound object?) must store this data somewhere.

like image 381
drosen Avatar asked Mar 12 '14 18:03

drosen


1 Answers

You can define your own function that processes the query entered by the user.

I made a sample fiddle: http://jsfiddle.net/dtengeri/6ApJg/

The basic idea is that you get the suggestions from the Bloodhound engine manually and only pass the required amount of results to typeahead.

// Custom source function in the dataset definition.
source: function (query, cb) { 
  // Get the data from the Blodhound engine and process it.
  nbaTeams.get(query, function (suggestions) {
    // Show only the first 3 results.
    cb(suggestions.slice(0, 3));
    // Set the headers content.
    $('#nba-header').text(suggestions.length);
  })
},

You have to define an HTML element inside the header template where you will put the number of results. (The span with the id #nba-header in this example.)

templates: {
  // Insert an HTML element where you will place the number of results.
  header: '<h3 class="league-name">NBA Teams (<span id="nba-header"></span>)</h3>'
}

In order to get all results you should set a high number as a limit in the Bloodhound engine:

var nbaTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: nba(),
  limit: Number.MAX_VALUE // Set the limit as high as possible.
});
like image 60
dtengeri Avatar answered Nov 06 '22 14:11

dtengeri