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);
}
});
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);
}
});
Share
Improve this question
edited Jul 2, 2021 at 17:57
Dimitar Dimitrov
asked Feb 12, 2013 at 7:32
Dimitar DimitrovDimitar Dimitrov
15.1k9 gold badges53 silver badges81 bronze badges
2
-
Possible dup: stackoverflow./questions/13743498/… - instead of the alert just use
.val('')
to empty the input field. – mccannf Commented Feb 12, 2013 at 8:50 - Thanks for the help, however that doesn't seem to do the trick -> check it jsfiddle/Q4DBx/1 – Dimitar Dimitrov Commented Feb 12, 2013 at 10:37
2 Answers
Reset to default 13If 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('');
}
});
The solution from mccannf works, but in my case with if(parents.indexOf($(this).val()) === -1) {
on blur event.