Bootstrap Typeahead using Solr and ColdFusion

As promised all the way back in February, (not really as soon as I would have liked) here is my entry on using Apache Solr and ColdFusion with Bootstrap Typeahead. Previously, I described how to accomplish this with JqueryUI, but with the increasing popularity of Bootstrap, I thought it would be good to add it to the examples.

This example will use the same Solr setup and CFC method (included in CFSolrLib 3.0) as our previous example. If you want to check out the instructions on how to set those up and build your dictionary your auto suggest terms will come from, you can see them here.

I'm using Bootstrap 2.3.2 and JQuery 1.10.2 in this sample. The JavaScript to call Typeahead on my input is as follows:


$(document).ready(function() {

$('#keyword').typeahead({
minLength: 1,

source: function(query, process) {
$.post('components/cfsolrlib.cfc?method=getAutoSuggestResults&returnformat=json&term=' + query, { limit: 8 }, function(data) {
var parJSON = JSON.parse(data);
                var suggestions = [];
                $.each(parJSON, function (i, suggestTerm) {
suggestions.push(suggestTerm);
});
                process(suggestions);
});
}
});
});

In the JS, I'm telling Bootstrap we're requiring the user to enter at least one character before we show any results. I'm posting to my cfc, passing the string the user has typed into the text box as the "query" variable and making sure to specify a return format of JSON. We're also specifying a limit of 8 results. In the JQuery UI example, we were relying on Solr to limit results. We have a little more control here. I then parse the returned JSON and use the push method to add the results to the suggestions array before calling Bootstrap's process method, returning the results to the input. There are a few more options I could pass to the typeahead method to update multiple inputs, do some custom hightlighting, etc, but for this example we'll keep it basic.

The HTML for our input is pretty basic:


Keyword: <input type="text" id="keyword" name="keyword" class="typeahead" data-provide="typeahead" autocomplete="off" />

I'm using the default "typeahead" style and specifying data-provide="typeahead" while making sure to turn autocomplete off so the browser doesn't try to trump my results.

A working example of the Bootstrap Typeahead version of the auto complete can be viewed at http://jimleether.com/solrexample/typeaheadExample.cfm.

For more ColdFusion and Solr fun, keep your browser pointed here!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Copyright © 2008 - Jim Leether BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.001. Contact Jim