City, State, County Selection With Bootstrap 2 Typeahead

This is a demonstration of how I implemented an Ajax call to a Perl Dancer2 Application using jQuery and the Bootstrap Typeahead function.

As part of my TravelTime App , I wanted to create and easy way to select the start and end locations using the jQuery Autocomplete component. Bootstrap 2 has its own version of this which they call Typeahead.
I just found out that the latest version of Bootstrap will not include this Typeahead functionality. Instead it will be replaced with typeahead.js I hope to check this out in the future.
Anyway, I will be using Perl, Dancer2 with Template Toolkit to render this form.
I also needed to customise the Typeahead to complete an Ajax call to my Perl Dancer2 application. The Dancer2 application will then provide the sorted list of City,States and Counties based on the search parameters passed to it.

The Template::Toolkit Form

Exerpt from travel_time_quick.tt

<div class="span11">
        <span class="text-info">
            <abbr title='Enter the starting location'>Start Location</abbr>
        </span>
        <div class="control-group">
        <!-- Bootstrap Typeahead -->
            <label class="control-label" for="address-[% loop.count %]">[% warning_message %]</label>
            <div class="controls">
                <input type="text"
                    class="cityStatesTypeahead span9 input-append"
                    name="address-[% loop.count %]"
                    id="address-[% loop.count %]" value="[% address %]"
                    placeholder="City/Town, State" 
                    autocomplete="off"
                    data-provide="typeahead"
                    required="required" 
                    autofocus
                    />
                    <span class="addQmark"><i class="iconic-question-mark"></i></span>
            </div>
            <input type="hidden"
                name="h-address-[% loop.count %]"
                id="h-address-[% loop.count %]"
                value=""
                />
            </div>
        </div> <!-- /span11 -->

The entire template can be seen here on GitHub.
The highlighted fields are the ones that are pertinent to the activation of the Bootstrap Typeahead.
In order to customise the Bootstrap Typeahead, I found this very useful website by FusionGrokker, for which I am thankful (You could also check out the jQuery docs for the original concept).

Here is my JavaScript to implement the Typeahead Ajax call.

The jQuery

Excerpt from city-states.js

var hiddenId;
// Get the hidden address field associated with the current
// address field
$('.cityStatesTypeahead').bind('focus',  function(){
   hiddenId =  $(this).attr('id'); 
});

$(".cityStatesTypeahead").typeahead({
  items: 10, 
  minLength : 3, 
  source:  function(query, process) {
      //Call Perl App to find the sorted list of City, States and Counties
      return searchForPlaces(query, process);
 },  
  highlighter: function(item){
    return highLightSelect(item);
},  

matcher: function () { return true; }, 
 
updater: function (item) {
    return updateField(item);
}, 

});
// Ajax call to Perl Dancer Script, which returns an Array Ref
// of sorted City, State and County data.
var debounceWait = 100;
// Use Underscore JS function '_debounce' to ensure that the
// search waits for specific number of milliseconds before running again.
var cityStates = {};
var cityNames = [];
var searchForPlaces = _.debounce(function( query,  process ){
    $.post("/city_states",{ find : query}, function(data){
    cityStates = {};
    cityNames = [];
        var counter = 0;
        _.each( data.city_states,  function( item,  ix,  list ){
        item.label = item + '-' + (counter++);
         // console.log('Got this item from AJAX : ' + item);
        cityStates[item.label] = {
                city : item[0],   
                state : item[1],  
                county : item[2]
        };
        //add selected items to diaplay array
        // console.log('Add this to the array ' + item.label);
        cityNames.push(item.label);

    });
    // Let Bootstrap and jQuery process the list
    // for display in the input box
    process( cityNames );
});
},  debounceWait);

//Highlighter Function
var highLightSelect = function(item){
    // console.log("      Item inside highlighter " + item);
   var c = cityStates[item];
   return ''
       + "<div class='typeahead_wrapper'>"
       + "<div class='typeahead_labels'>"
       + "<div class='typeahead_primary'>" + c.city + ', ' + c.state + "</div>"
       + "<div class='typeahead_secondary'><strong>County: </strong>"  + c.county + "</div>"
       + "</div>"
       + "</div>";
};

// Updater Function
// Add the required data into the input field
var updateField = function(item){
   var c = cityStates[item];
   //Hidden field will contain all the valuable data
    $( "#h-" + hiddenId ).val( c.city + ',' + c.state + ',' + c.county );
   //This is the data for display on input box
   return c.city + ', ' + c.state + "  County: " + c.county ;
};

//      END BOOTSTRAP TYPEAHEAD


Have a look at line 34 for the actual Ajax call to the Perl module. It sends a request to TravelTime.pm’s ‘/city_state’ route. As the Typeahead attribute ‘minLength’ is set to 3, it passes at least the first three letters of the requested City to the Dancer2 application. The city_states database is then searched for a city beginning with this search string. The Dancer2 application will return a sorted list of these cities with their corresponding state and county names. The application can also accept two search strings separated by a comma. This will search the database for cities beginning with the first string and corresponding states beginning with the second string.
“city-states.js” receives this sorted list of cities, states and counties.
The Typeahead displays (items: 10) items in the dropdown list.The “highLightSelect” highlighter function formats this list into a more readable format.
When an item is selected “theupdateField” populates the hidden fields.

More details of what is happening in TravelTime.pm will be left for another post.
Have a look at the TravelTime App in action.
I hope that this blog post may useful to some developer out there.