Asynchronous Auto-Complete Input Fields with Bootstrap

Bootstrap is a great HTML framework and I’ve been using it a lot lately for most of my projects.

The other day I needed to add asynchronous auto-complete functionality to an input field and Bootstrap seems to offer type ahead functionality out of the box. However, from the documentation it wasn’t instantly clear on how to implement this with an asynchronous ajax call to retrieve the data.

It turns out to be pretty straight forward:

1
2
3
4
5
6
7
8
9
10
$('#myinput').typeahead( {
  source: function( query, process ) {
    $.post("/get-data", {
      query: query
    },
    function( data ) {
      process(data);
    } );
  },
} );

Besides including the bootstrap.js file into your page, you also need to include bootstrap-typeahead.js to add the auto-complete functionality.

Your server script needs to return a single JSON array with the entries you want to appear in the drop-down list. Also note, for Chrome I noticed I had to add the autocomplete="off" parameter to my input tag to prevent it from displaying the built-in browser auto-complete drop-down.

This was tested with Bootstrap v2.2.2

This entry was posted in Programming. Bookmark the permalink. Both comments and trackbacks are currently closed.