Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 783
kcristella Avatar asked Dec 06 '12 12:12

kcristella


3 Answers

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? .

like image 93
Samuel Caillerie Avatar answered Oct 01 '22 01:10

Samuel Caillerie


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('');
    }
});
like image 23
Chad Scira Avatar answered Oct 01 '22 01:10

Chad Scira


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.

like image 21
jheyse Avatar answered Oct 01 '22 01:10

jheyse