如何在 Typeahead 中接受多个输入?

How to take multiple inputs in Typeahead?

我如何允许用户在预先输入的文本框中键入多个值,例如,他键入 ph 并弹出建议 php 然后他 selects 它,接下来他键入 da 和建议数据库弹出,他 select 也是。所以最后我输入框中的文本看起来像

php, databases

我应该如何实现这种效果?

我尝试了以下代码:

$(document).ready(function () {

    var getTags = new Bloodhound({
        datumTokenizer: function(d){ return Bloodhound.tokenizers.whitespace(d.result)},
        queryTokenizer: function(d){ return Bloodhound.tokenizers.whitespace(d)},
        remote: {
            url: 'query=plughere',
            wildcard: 'plughere'
        }
    });
    getTags.initialize();
    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'states',
        displayKey: 'name',
        source: getTags.ttAdapter(),        
    });

    $('.typeahead').bind('typeahead:selected typeahead:autocomplete', function(evt, item) {
        f = $('#hemo').val();
        $('#hemo').val(f + ", ");
    });

});

我将我的服务器编程为只考虑逗号后的最后一个词。

这里 hemo 是我的文本框的 id。一旦我 select 数据库,它就会删除之前已经输入的单词。因此,如果我先 select php 然后我 select 数据库,它会从文本框中删除 php 并向其中添加数据库。

Jsfiddle

如果我认为该绑定事件的第二个参数输出基于此 link 的值是正确的,那么您应该像这样使用它。

 $('.typeahead').bind('typeahead:selected typeahead:autocomplete', function(evt, item) {
    f = $('#hemo').val();
    $('#hemo').val(f + item.value + ", ");
 });

更新

在查看了您的 fiddle 之后,我认为您将有另一个文本框用于放置您选择的值。

我不确定这是否可能是您想要的,但作为解决方法,您可以将所有这些选定的值放在不同的文本框中。

样本:Fiddle