Auto tokenize last item in pasted string using select2

﹥>﹥吖頭↗ 提交于 2019-12-03 17:22:45
Luís Cruz

Based on a question that you have posted, you can use the following code that works with the variations:

1 2 3 4

1,2,3,4

1,2 3, 4

You can check this jsfiddle. Please note: I've found that version 3.5.0 has a bug with the third variation, so you should use the latest 3.5.1.

$("#select2-input").select2({
    tags: [''],
    tokenizer: function(input, selection, callback) {
        if (input.indexOf(',') < 0 && input.indexOf(' ') < 0)
            return;

        var parts = input.split(/,| /);
        for (var i = 0; i < parts.length; i++) {
            var part = parts[i];
            part = part.trim();

            callback({id:part,text:part});
        }
    }
});

I don't sure if I really understand your issue, but I've made a code to separate new input from paste function, Basically it overrides the default paste function to handle the new input text, this code will break the input based on the separators specified in the option 'tokenSeparators', then adds them all to the list separated, you only need to run this code at the end of your page:

$(document).on('paste', 'span.select2', function (e) {
        e.preventDefault();
        var select = $(e.target).closest('.select2').prev();
        var clipboard = (e.originalEvent || e).clipboardData.getData('text/plain');
        var createOption = function (value, selected) {
            selected = typeof selected !== 'undefined' ? selected : true;
            return $("<option></option>")
                .attr("value", value)
                .attr("selected", selected)
                .text(value)[0]
        };
        $.each(
            clipboard.split(new RegExp(select.data('select2').options.options.tokenSeparators.map(function (a) {
                return (a).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            }).join('|'))),
            function (key, value) {
                if (value && (!select.val() || (select.val() && select.val().indexOf('' + value) == -1))) {
                    select.append(createOption(value));
                }
            });
        select.trigger('change');
    });

You may review my original answer here https://stackoverflow.com/a/37006931/2073339

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!