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);
}
});
}
});
});
What is Typeahead? Typeahead - also known as autocomplete or autosuggest - is a language prediction tool that many search interfaces use to provide suggestions for users as they type in a query.
Performs search to retrieve list of places by input text and location vicinity. Address Autocomplete takes free form text as input. It could be a part of an address. Location could be provided either as latitude/longitude or as country ISO code. It returns consolidated list of addresses based on the input text.
jQuery plugin that provides Typeahead (autocomplete) Search preview from Json object(s) via same domain Ajax request or cross domain Jsonp and offers data compression inside Local Storage. The plugin is built with a lot of options and callbacks to allow customization.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With