Bootstrap Typeahead Only Allow List Values

Is it possible to limit a user's selection to the predefined data-source items for a Bootstrap Typeahead item? So if the user types something that is not in the data-source, a message is be displayed notifying them as such?

Here's the demo: http://cruiseoutlook.com/test


If I understand, when the typeahead component loses the focus, the user should be alerted that its input is invalid if it is not in the list?

The code will thus be something like this :

var myData = [...]; // This array will contain all your possible data for the typeahead

$("#my-type-ahead").typeahead({source : myData})
                   .blur(validateSelection);

function validateSelection() {
    if(source.indexOf($(this).val()) === -1) 
        alert('Error : element not in list!');
}

Just be careful about the fact that indexOf is not implemented in IE6-8. But shims can be found, for example : Best way to find if an item is in a JavaScript array? .


I ran into the same issue but in my situation all my my data was remote . Bloodhound doesn't really have any good hooks that i am currently aware of that lets you do this, but you can hook into the ajax complete callback and manually build up a valid input cache, and then check against that on change/blur.

var myData = new Bloodhound({
    remote: {
        url: '/my/path/%QUERY.json',
        ajax: {
            complete: function(response){
                response.responseJSON.forEach(function (item) {
                    if (myData.valueCache.indexOf(item.value) === -1) {
                        myData.valueCache.push(item.value);
                    }
                });
            }
        }
    }
});
myData.valueCache = [];
myData.initialize();

$('#artists .typeahead').typeahead(null, {
    source: myData.ttAdapter()
}).bind('change blur', function () {
    if (myData.valueCache.indexOf($(this).val()) === -1) {
        $(this).val('');
    }
});

Using jquery and Samuel's solution I think you will overcome the IE problem. Change your validateSelecion function to:

function validateSelection() {
    if ($.inArray($(this).val(), myData) === -1) 
        alert('Error : element not in list!');
}

Leave the rest as Samuel pointed out.

链接地址: http://www.djcxy.com/p/74956.html

上一篇: 在字符串中切换数字

下一篇: 引导类型只允许列表值