我在我的应用程序中使用Bootstrap Typeahead插件,这是我的代码(这是一个例子)。 我正在寻找一种方法来验证用户的选择(基本上如果输入与任何结果不匹配 - >清空模糊框)。结果必须匹配。我到处搜索,找不到东西。非常感谢您的帮助。
$('#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);
}
});
答案 0 :(得分:11)
如果您提取数据,状态和地图,则可以在.blur
函数中使用它们进行查找:
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('');
}
});
答案 1 :(得分:0)
来自mccannf的解决方案有效,但就我的情况而言,模糊事件为if(parents.indexOf($(this).val()) === -1) {
。