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 type
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.