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 li
The problem I have seen with some of these solutions, is that the source function is called repeatedly on every keyup event of the input box. Meaning, the arrays are being built and looped over on every keyup event.
This is not necessary. Using a closure, you can process the data only once, and maintain a reference to it from within the source function. In addition, the following solution solves the global namespace problem of @Gerbus's solution, and also allows you to play with the array of data once the user has selected something (for example, removing that item from the list).
// Setup the auto-complete box of users
var setupUserAcUi = function(data) {
var objects = [];
var map = {};
$.each(data, function(i, object) {
map[object.name] = object;
objects.push(object.name);
});
// The declaration of the source and updater functions, and the fact they
// are referencing variables outside their scope, creates a closure
$("#splitter-findusers").typeahead({
source: function(query, process) {
process(objects);
},
updater: function(item) {
var mapItem = map[item];
objects.splice( $.inArray(item, objects), 1 ); // Remove from list
// Perform any other actions
}
});
};
// `data` can be an array that you define,
// or you could pass `setupUserAcUi` as the callback to a jQuery.ajax() call
// (which is actually how I am using it) which returns an array
setupUserAcUi(data);