twitter-bootstrap Twitter Bootstrap Typeahead 强制选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14827576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Twitter Bootstrap Typeahead force selection
提问by Dimitar Dimitrov
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.
我在我的应用程序中使用 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);
}
});
回答by mccannf
If you extract out the data, states and map, you can then use them in the .blurfunction for lookup:
如果提取出数据、状态和地图,则可以在.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('');
}
});
回答by leompeters
The solution from mccannf works, but in my case with if(parents.indexOf($(this).val()) === -1) {on blur event.
mccannf 的解决方案有效,但在我的情况下if(parents.indexOf($(this).val()) === -1) {是模糊事件。

