Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created February 17, 2014 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save xeoncross/9060709 to your computer and use it in GitHub Desktop.
Save xeoncross/9060709 to your computer and use it in GitHub Desktop.
twitter typeahead.js plugin example usage
<!-- http://twitter.github.io/typeahead.js/data/repos.json -->
<input type="text" autocomplete="off" class="form-control"
id="client-search"
data-typeahead-url="./repos.json"
data-typeahead-target="client-id">
<input type="hidden" id="client-id" name="client-id">
// http://stackoverflow.com/questions/12413594/twitter-bootstrap-typeahead-get-context-calling-element-with-this
$(':input[data-typeahead-url]').each(function(){
var $this = $(this);
var engine = new Bloodhound({
name: 'somethinghere',
remote: {
url: $this.attr('data-typeahead-url') + '?query=%QUERY',
filter: function(list) {
return $.map(list, function(item) {
// Building a key out of all the object properties... probably not what you need so you can remove this
item._displayKey = $.map(item, function(value) { return value; }).join(',');
return item;
});
}
},
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$this.typeahead({
minLength: 2,
highlight: true,
hint: true
}, {
source: engine.ttAdapter(),
displayKey: '_displayKey',
valueKey: 'value',
items: 10
});
$this.on('typeahead:selected typeahead:autocompleted', function(event, datum) {
console.log(datum);
var $target = $('#'+$this.attr('data-typeahead-target'));
if($target.length) {
$target.val(datum.value);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment