Twitter Bootstrap comes packaged with a simple auto-complete library that’s stylistically integrated into the CSS framework. It’s convenient, but not the most-documented part of Bootstrap. I was working on a hobby project recently, and I wanted to have an auto-completing search field, but it took a bit of work to extend the basic implementation.
The first, and probably most important, step was to implement an AJAX data source. The plugin supports this out of the box, but the documentation page doesn’t have an example. It’s easy enough. You pass a function that takes the query and hands it off to one of jQuery’s magic asynchronous request functions, like so:
$(document).ready(function() {
$("#searchfield").typeahead({
minLength: 3,
source: function(query, process) {
$.post('/search/typeahead', { q: query, limit: 8 }, function(data) {
process(JSON.parse(data));
});
}
});
});
Your request URL needs to respond with a JSON array of strings, which the typeahead library will process. The variables “q” and “limit” are sent along with the POST request in this example, and a PHP back-end returns the relevant data in response.
Continue reading →












