Ibad Ibad - 5 months ago 456x
Javascript Question

JQuery Select2 - How to select all options

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 has to be implemented, I want to select/deselect options from this checkbox.


There is a description in thread on github. Quoting (https://github.com/ivaynberg/select2/issues/195#issuecomment-13489140 by MortadaAK) which allows you to select everything on ctrl+a

    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 = [];
            element.select2("val", selected);
        } else if (event.which == 100){
            element.select2("val", "");