Twitters Typeahead.js in Action

Lately I’ve been doing some light web development in my spare time. One feature I’ve been finding myself needing was an auto-completing combo box. We have such a feature built in to our product at SurroundTech, but since I was brushing up on my PHP skills instead of .Net that wasn’t an option. The requirements were typeahead functionality as well as the ability to drop down the results in as a combo box would showing the results based on the already entered string. Also, it has to retreive data from a service. If the data was all static I would probably just hard code it into a combo box for simplicity.

A made it through three different approaches before I settled on the Typeahead.js released by twitter.

The first solution I looked at was the JQuery UI autocomplete. This supports JSON services to populate the combox. The downside is it doesn’t autofill in the text in the actual text box, and when you tab off it doesn’t complete the entry. The other hurdle is that it didn’t seem to play nice with my twitter bootstrap styles right out of the box. I’ll admit, I’ve become a big fan of the bootstrap framework, as it really simplifies responsive layouts.

Next, I realized there was already an auto-complete option built into the Twitter Bootstrap framework. It seems this was done as a fork of the branch, and eventually was added to the official release. There isn’t much in the way of documentation on how to use it, but I worked from this example. The biggest issue I encountered is that it doesn’t to support complex types. The JQuery auto-complete didn’t, but it did support display string and value, which was good enough for me.

Finally, I decided to check out the new Typeahead.js by twitter. Not to be confused with the type ahead support in the bootstrap framework (version 2.0). Funnily enough, the bootstrap framework has dropped their previous implementation of type ahead for the typeahead.js version in the 3.0 version of bootstrap. RC1 just came out for Bootstrap V3.0, I’ll admit I haven’t tried it out yet.

Typeahead.js supports json web calls via ajax, as well as static values and the ability to pre-cache data-sets on page load.  It also auto-fills in the most relevant result in the text input field as you type. Most importantly, it supports complex types, and templateing of results.


There are already some solid examples on the typeahead.js page. I threw together an example you can download and try out as well.

If you’re using the bootstrap 2.0 framework, make sure you generate a custom package without the typeahead jquery option, as the two versions have some of the same signatures and can cause conflicts. 

You’ll need a simple php (or language of your choice) service to return the json results. This page returns a json string array based on the query string passed in to the ‘q’ parameter. This would normally go to a database, but for ease of use I’ve setup some static data.

<? 	header('Content-Type: application/json'); 	 	function startsWith($haystack, $needle) 	{ 	    return !strncmp(strtoupper($haystack), strtoupper($needle), strlen($needle)); 	} 	 	$data[] = "Abrams, J.J."; 	$data[] = "Connery, Sean"; 	$data[] = "Darwin, Charles"; 	$data[] = "Davis, Ben"; 	$data[] = "Davis, Patrick"; 	$data[] = "Drake"; 	$data[] = "Ellington, Duke"; 	 	$query = $_GET['q']; 	if(ISSET($query)) 	{ 		foreach ($data as $value) 		{ 			if(startsWith($value, $query)) 			{ 				$result[] = $value; 			} 		} 		echo json_encode($result);      	} 	else 	{ 		echo json_encode($data); 	} ?>

Now we add the code for our control. Try typing the letter ‘d’, I didn’t go to the trouble of adding a huge dictionary of names to the fake service.

<input class="typeahead tt-query" dir="auto" id="string-typeahead" spellcheck="false" style="position: relative; vertical-align: top; background-color: transparent;" type="text" autocomplete="off" placeholder="Search Contacts" />

Finally, the javascript code to make the magic happen. Jquery and the typeahead.js files are required. The %QUERY parameter will be set to whatever data is in the typeahead text box.

<script type="text/javascript" src="/demo/typeahead.js"></script><script type="text/javascript">// <![CDATA[
			name: 'contacts',
			remote: '',
// ]]></script>

For a full list of examples and features checkout the twitter typeahead page on github.

2 thoughts on “Twitters Typeahead.js in Action

  1. peter says:

    thank you for the the tutorial.
    i am trying to implement the same function but my results keep coming as undefined.

    i am getting data from a controller function. this is my function

    Public Function AjaxSearchJobPlu(ByVal q As String) As JsonResult
    Dim BId As New Guid(Session(“Bid”).ToString())
    Dim a = From BPD In vs.BPLUProducts
    Where BPD.PLU_Description.StartsWith(q) And BPD.BusinessDetailsId = BId
    Select BPD.PLU_ProductID, BPD.PLU_Description, BPD.MeasureSize, BPD.SimpleID
    Return Json(a, JsonRequestBehavior.AllowGet)
    End Function

    and my script

    name: ‘contacts’,
    remote: ‘/Stocktaker/AjaxSearchJobPlu/?q=%QUERY’,

    please help

  2. Patrick says:

    My VB is a little rusty (and by that I mean I’ve never used it).

    First thing I would try is typing your service URL right into the browser and make sure you’re getting back what you are expecting.

    In my example my text box has the id of ‘#string-typeahead’ make sure you’re is the same in your html so the jquery finds the right code.

    Next step is to hit F12 and go to the developers console. Check the ‘Console’ for any error messages.

    If there are no error messages, In Chrome there is a network tab. You can make sure your script is making the right ajax calls when you type into your type ahead box.

    It’s hard to get into too much detail without an error message. If you can locate one, it should be an easy fix.

    Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *