Pierre de LESPINAY Pierre de LESPINAY - 1 year ago 227
Javascript Question

Twitter Bootstrap Typeahead - Id & Label

I'm using bootstrap 2.1.1 and jquery 1.8.1 and trying to use typeahead's functionality.

I try to display a label and use an id like a standard

<select />

Here is my typeahead initialization:

source: function (query, process) {
$('#autocompleteForm .query').val(query);
return $.get(
, $('#autocompleteForm').serialize()
, function (data) {
return process(data);

Here is the kind of json that I'm sending


How can I tell
to display my labels and store the selected id in another hidden field ?

Answer Source

There's a great tutorial here that explains how to do this: http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/ (read my comment on that page if it hasn't been reflected yet in the main part of the post).

Based on that tutorial, and the JSON you provided, you can do something like this:

    source: function(query, process) {
        objects = [];
        map = {};
        var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
        $.each(data, function(i, object) {
            map[object.label] = object;
    updater: function(item) {
        return item;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download