Selectable optgroup using select2

后端 未结 8 576
醉话见心
醉话见心 2020-12-02 21:20

I have used select2 to select multiple options from a drop down, but is it possible for select2 to select the full optgroup?? What I want is when user select the option grou

相关标签:
8条回答
  • 2020-12-02 22:12

    I've used John's code, but my problem was that I needed the ability to filter, so I added it. You can see the code working on jsfiddle.

    This is the query code:

             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 });
            }
    
    0 讨论(0)
  • 2020-12-02 22:18

    First give id to your select for example

    <select style="width: 95%" id="selectgroup">

    and then add class to your optgroup like

     <optgroup value="ATZ" label="Alaskan/Hawaiian Time Zone" class="select2-result-selectable">
    

    and then add this

    $('#selectgroup').select2({
    
        }).on('select2-selecting', function (e) {
            debugger;
            var $select = $(this);
            if (e.val == undefined) {
                e.preventDefault();
                var childIds = $.map(e.choice.children, function (child) {
                    return child.id;
                });
                $select.select2('val', $select.select2('val').concat(childIds));
                $select.select2('close');
           }
        });
    

    If you click on optgroup then It will select all the options under the optgroup.

    0 讨论(0)
提交回复
热议问题