Skip to content

Instantly share code, notes, and snippets.

@mjradwin
Created December 23, 2014 16:35
Show Gist options
  • Save mjradwin/d4869c2ccc0496b78228 to your computer and use it in GitHub Desktop.
Save mjradwin/d4869c2ccc0496b78228 to your computer and use it in GitHub Desktop.
<div id="city">
<input type="text" class="typeahead" placeholder="Search for city">
</div>
var cities = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/complete.php?q=%QUERY',
limit: 8
});
cities.initialize();
$('#city .typeahead').typeahead(null, {
name: 'city',
displayKey: 'value',
source: cities.ttAdapter(),
templates: {
empty: function(ctx) {
var encodedStr = ctx.query.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
return '<div class="tt-suggestion">Sorry, no city names match <b>' + encodedStr + '</b>.</div>';
},
suggestion: function(ctx) {
var country = ctx.country || '',
s = '<p><strong>' + ctx.asciiname + '</strong>';
if (country && typeof ctx.admin1 === "string" && ctx.admin1.length > 0 && ctx.admin1.indexOf(ctx.asciiname) != 0) {
country = ctx.admin1 + ', ' + country;
}
if (country) {
country = ' - <small>' + country + '</small>';
}
return s + country + '</p>';
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment