I'm trying to use Twitter's typeahead.js on a field ("#addtags") to suggest tags to add, but when I select something the field keeps the value I just entered when it should be cleared.
I've tried the solution provided here (Set selected value of typeahead) which is to use $("#id").typeahead('setQuery', query); to clear the field. However, when I do that I get an error in my console: Uncaught Error: missing source.
Is there a way around this? The code to clear the field is a line above the bottom, rest provided for context.
//===========================
//Typeahead.js
//===========================
var tagApi = $("#addtags").tagsManager();
var addtags = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d['tag']); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
dupChecker:true,
// remote: '/tags/tags/search.json?q=%QUERY',
prefetch: {url: '/tags/tags/search.json?q='}
});
addtags.initialize();
$('#addtags').typeahead({
hint:true,
highlight:true,
autoselect:false,
dupChecker:true,
},
{
displayKey: 'tag',
source: addtags.ttAdapter(),
}).on('typeahead:selected', onTagSelect);
function onTagSelect($e, datum) {
tagApi.tagsManager("pushTag", datum['tag']);
//This is where I'm trying to clear the input:
$('#addtags').typeahead('setQuery', '');
};
I've created a jsfiddle to show how to clear the selected suggestion:
http://jsfiddle.net/Fresh/ecq0c0ph/
Try searching for a movie and then select a suggestion; the suggestion will be used to populate some fields and then the query input control will be cleared.
In a nutshell, to clear the suggestion when it is selected, create an event handler for Typeahead's selected event, and then use its API to set the value to an empty string e.g.
.bind("typeahead:selected", function () {
$('.typeahead').typeahead('val', '');
});
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