Cameron Cameron - 1 month ago 19
jQuery Question

Handling objects with Twitter Bootstrap Typeahead

I'm using the Bootstrap Typeahead plugin like so:

$('#Organisation').typeahead({
source: function (query, process) {
return $.get(AppURL + 'Organisations/Manage/SearchByName/',
{
term: query
},
function (data) {
var results = [];
var fullResults = [];
$.each(data, function (index, item) {
results.push(item.label);
fullResults.push({
id: item.ID,
label: item.label
});
});

return process(results);


});
},
updater: function (selection) {
$('#OrganisationID').val(selection);
}
});


I have two returned arrays, this is because Typeahead ONLY wants a list of strings instead of an object. The second array contains both the label and id.

Once a user selects an item from the list I need to get the ID from this selection and then use it to insert into a hidden field. But the selection will just be the name, as the ID can't be passed through via Typeahead.

Any ideas on how I can solve this?

An example of the two returned arrays:

results:
["Organisation 1","Organisation 2"]


fullResults:
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]

Answer

After searching around a bit on the net I found this HowTo. In it they do what you want, but with no ajax.

You should also be able to return a object, from the source function, but you would need to re-implement all the helper functions of typeahead.

Comments