使用select2 multiple select填充选定的值

时间:2016-04-13 15:41:08

标签: javascript jquery onload select2

我有一个select2从下拉列表中选择多个选项,我也选择了多个选项。无论如何通过以某种方式更改其值来填充在页面加载时选择的值的输入字段,因此当加载页面时,已经选择了选项。

我的代码的一部分如下:

 $('#fruitSelect').select2({
            multiple: true,
            placeholder: "Select fruits...",
            data: FRUIT_GROUPS,
            query: function (options) {
                var selectedIds = options.element.select2('val');
                var data = jQuery.extend(true, {}, FRUIT_GROUPS);
                var selectableGroups = $.map(data, function (group) {
                    var areAllChildrenSelected = true,
                        parentMatchTerm = false,
                        anyChildMatchTerm = false;
                    if (group.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0) {
                        parentMatchTerm = true;
                    }
                    var i = group.children.length
                    while (i--) {
                        var child = group.children[i];

                        if (selectedIds.indexOf(child.id) < 0) {
                            areAllChildrenSelected = false;
                        };

                        if (options.term == '' || (child.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0)) {
                            anyChildMatchTerm = true;
                        }
                        else if (!parentMatchTerm) {
                            var index = group.children.indexOf(child);
                            if (index > -1) {
                                group.children.splice(index, 1);
                            };
                        };
                    };

                    return (!areAllChildrenSelected && (parentMatchTerm || anyChildMatchTerm)) ? group : null;
                });

                options.callback({ results: selectableGroups });
            }
        }).on('select2-selecting', function (e) {
            var $select = $(this);
            if (e.val == '') {
                e.preventDefault();
                $select.select2('data', $select.select2('data').concat(e.choice.children));
                $select.select2('close');
            }
        });

JS Fiddle

0 个答案:

没有答案