limit results

typeahead – Limit results

Posted on: February 28th, 2014 by taff No Comments

 

I recently started using twitters typeahead for search suggestions. Although it works well out of the box, there were a couple of things I wanted to change. Currently I have typeahead doing two requests, one that retrieves the searchterms other users have used and the other to find relevant products in a database, but to start let's look how to go about limiting the number of results.

Limiting the number of results with typeahead

By default, typeahead limits the number of results to 5. I, however, only wanted the 3 closest results. Limiting the number of results with typeahead is simply achieved using the limit parameter as can be seen in the typeahead example below

jQuery('#Search').typeahead([
{
limit: 3,
remote: '/searchterms.php?q=%QUERY',
name: 'searchterms'
}
]);

The example has three parameters, the limit parameter that tells typeahead how many results to display, the remote parameter which tells typeahead where to get the data from and name which tells typeahead the name of the dataset. The code above limits the results to three. As you can see limiting the number of results with typeahead is a breeze with the correct parameter.

This code needs to be placed inside a document ready function or an equivalent to ensure execution when the page has loaded. It goes without saying but you obviously need to make a script call to typeahead.min.js. In the example above typeahead adds some javascript magic to the input field with the ID Search.

Although not entirely related to limiting the number of results with typeahead, in addition to the remote parameter, there are other ways of retrieving data. For example, if you have a set amount of data that you want to be cached client side, you may want to look into the prefetch parameter. I hope you like this short example of limiting the number of results with typeahead. Look forward to a couple of other examples such as requesting more than one type of data and how to build a custom template without using hogan.