JQuery Select2 - How to select all options

后端 未结 18 800
死守一世寂寞
死守一世寂寞 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:22

    Please see below code.

    $('.select2').select2({
        formatResult:function(object, container, query){
            if(object.id=='all' || object.id=='clear')
                return ' '+object.text+'';
    
            return object.text;
        }
    });
    $('.select2').on("change", function(e) {
        if($.inArray('all', e.val)===0){
            var selected = [];
            $(this).find("option").each(function(i,e){
                if($(e).attr("value")=='all' || $(e).attr("value")=='clear')
                    return true;
    
                selected[selected.length]=$(e).attr("value");
            });
            $(this).select2('val',selected);
        }else if($.inArray('clear', e.val)===0){
            $(this).select2('val','');
        }
    });
    

    Reference from: https://github.com/select2/select2/issues/195#issuecomment-52163095

提交回复
热议问题