I'm using the Bootstrap Typeahead plugin in my app, and here is my code (it's an example). I'm looking for a way to validate the selection of the user (basically if the input did not match any results -> empty the box on blur). The result must match. I searched everywhere and couldn't find a thing. Your help would be highly appreciated.
$('#search').typeahead({
source: function (query, process) {
var states = [];
var map = {};
var data = [
{ "stateCode": "CA", "stateName": "California" },
{ "stateCode": "AZ", "stateName": "Arizona" },
{ "stateCode": "NY", "stateName": "New York" },
{ "stateCode": "NV", "stateName": "Nevada" },
{ "stateCode": "OH", "stateName": "Ohio" }
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
});
If you extract out the data, states and map, you can then use them in the .blur
function for lookup:
var data = [
{ "stateCode": "CA", "stateName": "California" },
{ "stateCode": "AZ", "stateName": "Arizona" },
{ "stateCode": "NY", "stateName": "New York" },
{ "stateCode": "NV", "stateName": "Nevada" },
{ "stateCode": "OH", "stateName": "Ohio" }
];
var states = [];
var map = {};
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
$('#search').typeahead({
source: function (query, process) {
process(states);
}
}).blur(function(){
if(states[$(this).val()] == null) {
$('#search').val('');
}
});