I am using the Twitter typeahead.js header and the following is my code that works. However i would like to know if there was a way I could populate my dataset using a function instead of an array in local. Your help is much appreciated.
<input id="look" placeholder="search" autocomplete="off" />
<button id="btn">Submit</button>
<script type="text/javascript">
$("#look").typeahead({
name: 'accounts',
//Would like to use a function to populate my dataset here instead of this array
local: ['timtrueman', 'JakeHarding', 'vskarich']
});
$("#btn").click(function () {
$("#look").typeahead('setQuery', 't');
$("#look").focus();
});
</script>
</body>
Since local provides only static data, I think remote suits your need better:
$('#look').typeahead({
name: 'accounts',
remote: '/your/backend/url?q=%QUERY'
});
So typeahead will send AJAX request to /your/backend/url with parameter q with value is the value you type. Your backend should be able to return a response for that lookup request.
If you want to debug the response from your backend and process that data, use this:
$('#look').typeahead({
name: 'accounts',
remote: {
url: '/your/backend/url?q=%QUERY',
filter: function(resp) {
var dataset = [];
console.log(resp); // debug the response here
// do some filtering if needed with the response
return dataset;
}
}
});
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With