Created
February 17, 2014 22:41
-
-
Save xeoncross/9060709 to your computer and use it in GitHub Desktop.
twitter typeahead.js plugin example usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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"> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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