Twitter Bootstrap Typeahead强制选择 [英] Twitter Bootstrap Typeahead force selection

查看:66
本文介绍了Twitter Bootstrap Typeahead强制选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用Bootstrap Typeahead插件,这是我的代码(这是一个示例). 我正在寻找一种验证用户选择的方法(基本上,如果输入不匹配任何结果->清空模糊框).结果必须匹配.我到处搜寻,找不到任何东西.非常感谢您的帮助.

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);
        }
    });

推荐答案

如果您提取数据,状态和地图,则可以在.blur函数中使用它们进行查找:

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('');
    }
});

这篇关于Twitter Bootstrap Typeahead强制选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆