Selectable optgroup using select2

后端 未结 8 611
醉话见心
醉话见心 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 21:52

    In Select2 v4, I found that John S's answer won't work (see here). I am loading my data as an array using AJAX and created a workaround:

    $(document).on("click", ".select2-results__group", function(){
        var input = $(this);
        var location = input.html();
        // Find the items with this location
        var options = $('#select2 option');
        $.each(options, function(key, value){
            var name = $(value).html();
            // The option contains the location, so mark it as selected
            if(name.indexOf(location) >= 0){
                $(value).prop("selected","selected");
            }
        });
        $("#select2").trigger("change");
    });
    

    I am grouping my items by location, and each option contains the location name somewhere in it's html. Any time an optgroup header is clicked, I get it's location (the name displayed in the dropdown). Then I look through all options in the #select2 table and find which ones contain that location in its html.

    I know this is a hacky workaround, but hopefully it helps/points in the right direction.

提交回复
热议问题