bootstrap typeahead return name and id

iMoldovean.com picture iMoldovean.com · Jan 3, 2013 · Viewed 40.5k times · Source

Hy! I'm using twitter bootstraps typeahead:

I'm calling a page that returns a response with json_encode the page returns a name and an ID,

I want that the typeahead list will show me the list of names, and when I select one of the name to write the id value to a hidden field.

the calling works fine, and to write a field should be easy. what i dont know what to do is how to divide the name from the id.

now, when i search something, in the suggesstion list I can see the returning results like this:

name1:id1 name2:id2

i only want to see names but to carry the value of id too.

how can i do that?

 $(function(){
    $("#typeahead_<? print $key; ?>").typeahead(
        {
        source: function(query, process)
                    {
                    $.ajax({
                        url:    '/getAjaxProducts',
                        type:   'POST',
                        data:   'query=' + query,
                        dataType: 'JSON',
                        async: true,
                        success: function(data)
                                {
                                process(data);
                                }
                            });                 
                    }
        });
});

Answer

Corby Page picture Corby Page · Jan 4, 2013

A typical JSON document that contains name/ID pairs is going to look like this:

[
  {
    "id": 1
    "name": "firstName"
  },
  {
    "id": 2
    "name": "secondName"
  }
]

The strategy here is to build an object literal that maps names to IDs as you parse the result, while only using the name to populate the typeahead:

var productNames = new Array();
var productIds = new Object();
$.getJSON( '/getAjaxProducts', null,
        function ( jsonData )
        {
            $.each( jsonData, function ( index, product )
            {
                productNames.push( product.name );
                productIds[product.name] = product.id;
            } );
            $( '#product' ).typeahead( { source:productNames } );
        } );

Once the user selects an item from the typeahead, you can reference the selected item with:

$( '#product' ).val()

and you can get the ID associated with the selected item with:

productIds[$( '#product' ).val()]

From your question, it looks like your JSON document may be structured a little bit differently, so you would change the parsing as appropriate, but the same general strategy applies.