Skip to content

Instantly share code, notes, and snippets.

@monkbroc
Created March 5, 2015 22:05
Show Gist options
  • Select an option

  • Save monkbroc/4ca08f17cb0dc5bf38e1 to your computer and use it in GitHub Desktop.

Select an option

Save monkbroc/4ca08f17cb0dc5bf38e1 to your computer and use it in GitHub Desktop.
"Add new..." for Typeahead.js
$(function() {
var source = new Bloodhound({
/* create source as usual... */
});
source.initialize();
// Check if the query matches exactly
function noDirectMatch(matches, query) {
if (matches.length > 0 ) {
return matches[0][Object.keys(matches[0])[0]].toLowerCase() != query.toLowerCase();
} else {
return true
}
};
// Create an intermediate typeahead source that adds a special "noMatch"
// suggestion unless the query matches exactly
var ttAdapter = function(query, cb) {
source.get(query, function(matches) {
if (noDirectMatch(matches, query)) {
matches.push({
noMatch: true,
query: query
});
}
cb(matches);
});
};
var $input = $('#search');
$input.typeahead({}, {
displayKey: 'name',
source: ttAdapter,
templates: {
// Render the "noMatch" suggestion in a special way
suggestion: function(suggestion) {
if (suggestion.noMatch) {
return "Add " + suggestion.query;
} else {
return suggestion.name;
}
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment