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:
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.
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.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With