How to prevent duplicate with Bootstrap Tokenfield When using Jquery Ui Autocomplete

前端 未结 4 2030
抹茶落季
抹茶落季 2021-02-06 05:06

I am trying to implement Bootstrap Tokenfield with Jquery Ui autocomplete and so far i was able to do that except the fact that i am not able to prevent duplicates in the input

4条回答
  •  我在风中等你
    2021-02-06 05:51

    @Javier Your solution work good but sometimes it gets buggy and add twice the token! Have you got idea for this behaviour?

    PS After seen the documentation i found the solution. Both event handling are needed. Because events are fired before and after creation/edit/remove of tokens.

    So you need this to prevent the add (before create event)

    $('#tokenfield').on('tokenfield:createtoken', function (event) {
        var existingTokens = $(this).tokenfield('getTokens');
        //check the capitalized version
        event.attrs.value =  capitalizeFirstLetter(event.attrs.value);
        $.each(existingTokens, function(index, token) {
            if (token.value === event.attrs.value) {
                event.preventDefault();
                return false;
            }
        });
    });
    

    And this other too, as you suggested, for the source-list (after create event)

    $('#tokenfield').on('tokenfield:createdtoken tokenfield:removedtoken', function (event) {
        var field = $(this);
        var currentTokens = field.tokenfield('getTokens').map(function(i){return i.value});
        var originalSource = field.data('bs.tokenfield').options.autocomplete.source;
        var newSource = [];
        for (var i = 0; i

    NOTE: I changed the "check loop", (double for was overkilling), and added a check to avoid "capitalized" matching, just in case you need it.

    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    

提交回复
热议问题