Skip to content

Instantly share code, notes, and snippets.

@takemyoxygen
Created May 29, 2013 10:10
Show Gist options
  • Save takemyoxygen/5669297 to your computer and use it in GitHub Desktop.
Save takemyoxygen/5669297 to your computer and use it in GitHub Desktop.
$.fn.asyncTypeahead = function (options) {
var defaultTypeaheadOptions = {
queryParameter: "query",
minLength: 1,
items: 10
};
options = $.extend(defaultTypeaheadOptions, options);
function serializeItem() {
// Custom JSON serialization
return '{"id":' + this.id + ', "text":' + '"' + this.text + '"' + '}';
}
$(this).typeahead({
source: function (query, process) {
var data = {};
data[options.queryParameter] = query;
$.get(options.source, data, function (result) {
for (var i = 0; i < result.length; i++) {
result[i].toString = serializeItem;
}
process(result);
}, "json");
},
updater: function (itemText) {
var item = $.parseJSON(itemText);
//TODO insert item.id into a hidden field
return item.text;
},
highlighter: function (item) {
var additionalHtml = "";
if (item.additional) {
additionalHtml = "<br/>" + item.additional;
}
return "<span><strong>" + item.text + additionalHtml + "</strong></span>";
},
items: options.items,
minLength: options.minLength,
sorter: function (items) { return items; },
matcher: function () { return true; }
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment