Created
March 5, 2015 22:05
-
-
Save monkbroc/4ca08f17cb0dc5bf38e1 to your computer and use it in GitHub Desktop.
"Add new..." for Typeahead.js
This file contains hidden or 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
| $(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