Bootstrap Typeahead Only Allow List Values

前端 未结 4 1518
轻奢々
轻奢々 2020-12-14 09:52

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

4条回答
  •  有刺的猬
    2020-12-14 10:51

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

提交回复
热议问题