JQuery Select2 - How to select all options

后端 未结 18 733
死守一世寂寞
死守一世寂寞 2020-12-02 10:50

I\'m using jQuery select2 multi select dropdown. I need to select all options in a dropdown from code. Basically there is a Select All checkbox on which this functionality h

18条回答
  •  一向
    一向 (楼主)
    2020-12-02 11:14

    @Garath: I have tweaked your posted code in order to make it work with results that are loaded via ajax. Thank you for bringing this up here.

        $(document).on("keypress",".select2-input",function(event){
        if (event.ctrlKey || event.metaKey) {
            var id =$(this).parents("div[class*='select2-container']").attr("id").replace("s2id_","");
            var element =$("#"+id);
            if (event.which == 97){
                var selected = [];
                $('.select2-drop-active').find("ul.select2-results li").each(function(i,e){
                    selected.push($(e).data("select2-data"));
                });
                element.select2("data", selected);
            } else if (event.which == 100){
                element.select2("data", []);
            }
        }
    });
    

提交回复
热议问题