Select2 将值从一个 select2 复制到另一个

Select2 Copy values from one select2 to another

我有一个全局 select2 控件,当单击一个按钮时,我想获取选定的值并用它们填充其他各种 select2 控件。

如何将选定值从一个 select2 控件复制到另一个控件?

我试过以下方法:

//Set Up control where values will copy to
$(hashElement).select2({
            multiple: true,
            data: Details,
            initSelection: function (element, callback) {
                data = $.parseJSON(element.val());
                callback(data);
            }
        });


var ApplyGlobalValues = function () {
        // get hashtag values 
        var values = $("#SelectGlobal").select2("val");
        $(".select-children").select2('val', values).trigger("change");
    }

该按钮触发 ApplyGlobalValues() 并点击了 initSelection,但未填充值。我究竟做错了什么?

下面我创建了一个示例,将一个 select2 的值复制到另一个 select2。第一个技巧是,当您使用 initSelection 时,您必须在 html 输入元素上设置默认值属性。第二个技巧是,您必须获取 select2 元素的 'data' 属性 而不是 'val' 属性 才能将值作为对象数组获取。

HTML:

<input id="select2example1" type="hidden" value="1,1,2">
<input id="select2example2" type="hidden" value="1,1,2">
<input type="button" id="mybutton" value="copy to other select2">

JS:

var data = [{
        id: 1,
        text: "A"
    }, {
        id: 2,
        text: "B"
    }, {
        id: 3,
        text: "C"
    }];


    $("#select2example1").select2({
        multiple: true,
        data: data,
        initSelection: function (element, callback) {
            var data = [{ id: 1, text: 'A' }, { id: 3, text: 'C' }];
            callback(data);
        }
    });

    $("#select2example1").select2('val', '1,2');

    var ApplyGlobalValues = function () {

        var values = $("#select2example1").select2("data");
        $('#select2example2').select2({
            multiple: true,
            data: data,
            initSelection: function (element, callback) {
                var data = values;
                callback(data);
            }
        });
    }

    $("#mybutton").click(function () {
        ApplyGlobalValues();
    });

另请参阅: http://jsfiddle.net/08us1mg5/