Tokenfield - 仅允许来自源的令牌

时间:2016-02-24 18:31:33

标签: jquery bootstrap-tokenfield

我正在尝试使用Tokenfield插件 - http://sliptree.github.io/bootstrap-tokenfield

如何限制仅使用来自源的令牌?

$('#tokenfield_platform').tokenfield({
autocomplete: {
source: [
        {% for platform_item in platforms %}
        '{{ platform_item }}',
    {% endfor %}
],
delay: 100
},
createTokensOnBlur:true,
showAutocompleteOnFocus: true
}).on('tokenfield:createtoken', function (event) {
    var existingTokens = $(this).tokenfield('getTokens');
    $.each(existingTokens, function(index, token) {
    if (token.value === event.attrs.value)
        event.preventDefault();
    });
    //var available_tokens = bloodhound_tokens.index.datums;
    // I do not want to use Twitter Typeahead, but only tokens from source
    var exists = true;
    $.each([available_tokens, function(index, token) {
    if (token.value === event.attrs.value)
        exists = false;
    });
    if(exists === true)
    event.preventDefault();
});

感谢您的任何信息。

1 个答案:

答案 0 :(得分:2)

使用侦听器令牌字段:createtoken ,您可以在创建令牌之前验证令牌。

信息:http://sliptree.github.io/bootstrap-tokenfield/#events

$('#tokenfield_platform').on('tokenfield:createtoken', function (event) {
    var exists = false;
    $.each(yourSource, function(index, value) {
            if (event.attrs.value === value) {
                exists = true;
            }
    });
    if(!exists) {
            event.preventDefault(); //prevents creation of token
    }
});