I have a textbox where I am using auto-complete via Twitter Typeahead, specifically the remote example.
Here is my code:
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: getStateUrl + "?query=%QUERY",
wildcard: '%QUERY'
}
});
var sLength = states.length; // this comes back as undefined
$('#StateName').typeahead({
highlight: true
}, {
name: 'states',
display: 'state',
source: states,
limit: 10
}).bind('typeahead:select', function(ev, suggestion) {
$("#StateId").val(suggestion.id);
});
If you did not see the comment in my code, states.length
returns as undefined
. I have tried states.index.datums.length
but that too comes back as undefined
.
How do I get the length
or count
of states
using the remote twitter typeahead?
As @Sai-nihar-nightraiser said, you're trying to set the length of results before results have been gathered. Try it like this:
var sLength;
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: getStateUrl + "?query=%QUERY",
wildcard: '%QUERY',
filter: function (statesResults){
window.sLength = statesResults.length;
return statesResults;
}
});
sLength should be equal to the number of states returned after typeahead is run. I got the info from this post: Typeahead.js - Show that there are more results