Skip to content

Instantly share code, notes, and snippets.

@tacone
Last active December 11, 2015 02:58
Show Gist options
  • Save tacone/4534615 to your computer and use it in GitHub Desktop.
Save tacone/4534615 to your computer and use it in GitHub Desktop.
How to manage structured data with Bootstrap typeahead.
/* bad indentation is NetBeans' fault, camelCase is Propel's fault */
var retrieveTeachers = function(query, process) {
// let them be json
var transformTeachers = function(teachers) {
return $.map(teachers, function(teacher) {
return {
id: teacher.Id,
FullName: (teacher.Name + ' ' + teacher.Surname),
// these functions allows Bootstrap typehead to use this item in places where it was expecting a string
toString: function() {
return JSON.stringify(this);
},
toLowerCase: function() {
return this.FullName.toLowerCase();
},
indexOf: function(string) {
return String.prototype.indexOf.apply(this.FullName, arguments);
},
replace: function(string) {
return String.prototype.replace.apply(this.FullName, arguments);
}
};
});
}
$.ajax({
url: $(this)[0].$element[0].dataset.url,
type: 'post',
data: {query: query},
dataType: 'json',
success: function(data) {
return typeof data == 'undefined' ? false : process(transformTeachers(data))
}
});
};
$('.teacher-typeahead').typeahead({
source: retrieveTeachers
, updater: function(json) {
console.log(json);
var item = $.parseJSON(json);
console.log('chosen id:' + item.id);
updateMyDiv('#lol', item);
return item.FullName;
}
, items: 8
, menu: '<ul class="typeahead dropdown-menu"></ul>'
, item: '<li><img src="//placehold.it/40x40"/><a href="#"></a></li>'
})
@Yohn
Copy link

Yohn commented Jan 15, 2013

source: retrieveTeachers
wheres retrieveTeachers ?

from what I can see I like how you did this.. its better than my hacked version I tried to do which doesnt event use typeahead anymore =/

@tacone
Copy link
Author

tacone commented Jan 18, 2013

I fixed the Gist (changed the first line). This is out of memory, hope that works.

@jordanhammond
Copy link

Thanks for this. However if my ajax call returns the image urls how do I use them in the dropdown?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment