Is it possible to limit a user's selection to the predefined data-source items for a Bootstrap Typeahead item? So if the user types something that is not in the data-source, a message is be displayed notifying them as such?
Here's the demo: http://cruiseoutlook.com/test
If I understand, when the typeahead component loses the focus, the user should be alerted that its input is invalid if it is not in the list?
The code will thus be something like this :
var myData = [...]; // This array will contain all your possible data for the typeahead
$("#my-type-ahead").typeahead({source : myData})
.blur(validateSelection);
function validateSelection() {
if(source.indexOf($(this).val()) === -1)
alert('Error : element not in list!');
}
Just be careful about the fact that indexOf
is not implemented in IE6-8. But shims can be found, for example : Best way to find if an item is in a JavaScript array? .
I ran into the same issue but in my situation all my my data was remote. Bloodhound doesn't really have any good hooks that i am currently aware of that lets you do this, but you can hook into the ajax complete callback and manually build up a valid input cache, and then check against that on change/blur.
var myData = new Bloodhound({
remote: {
url: '/my/path/%QUERY.json',
ajax: {
complete: function(response){
response.responseJSON.forEach(function (item) {
if (myData.valueCache.indexOf(item.value) === -1) {
myData.valueCache.push(item.value);
}
});
}
}
}
});
myData.valueCache = [];
myData.initialize();
$('#artists .typeahead').typeahead(null, {
source: myData.ttAdapter()
}).bind('change blur', function () {
if (myData.valueCache.indexOf($(this).val()) === -1) {
$(this).val('');
}
});
Using jquery and Samuel's solution I think you will overcome the IE problem. Change your validateSelecion function to:
function validateSelection() {
if ($.inArray($(this).val(), myData) === -1)
alert('Error : element not in list!');
}
Leave the rest as Samuel pointed out.
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