Is it possible to paste a list to a select2 field and match each item in the list?

眉间皱痕 提交于 2019-11-28 06:01:28
igor.vaynberg

select2 provides a tokenizer option that lets you pre-process the input. here is a possible implementation for your particular usecase:

tokenizer: function(input, selection, callback) {

        // no comma no need to tokenize
        if (input.indexOf(',')<0) return;

        var parts=input.split(",");
        for (var i=0;i<parts.length;i++) {
            var part=parts[i];
            part=part.trim();
            // todo: check for dupes (if part is already in [selection])

            // check if the part is valid
            // todo: you will need a better way of doing this
            var valid=false;
            for (var j=0;j<unitIds.length;j++) {
                if (part===unitIds[j]) { valid=true; break; }
            }

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

here is a working fiddle: http://jsfiddle.net/XcCqg/38/

also note your original fiddle uses select2 3.2 which is very outdated and may not support the tokenizer.

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