Close ANY Select2 dropdowns via jQuery
Asked Answered
D

1

0

Anyone know how to close a Select2 programatically without knowing the ID? Just basically, if there's a Select2 open, close it.

(If someone opens a modal (containing a Select2), opens the dropdown, and then clicks away from / dimisses the modal, the modal closes but the Select2 continues to show until another click.)

For instance, this works BUT you need to know the ID:

// If a Modal is hidden, close the Select2 contained therein
$(document).on('hide.bs.modal', '.modal', function() {
    $("#myDropdown").select2("close");
});

And this (selecting by class) doesn't work - at least for me:

$(document).on('hide.bs.modal', '.modal', function() {
    $(".select2").select2("close");
});

I know there are other similar topics, but I've reviewed a bunch and am not finding a solution.

Such as this: close select2 dropdown via javascript/jquery

Any ideas?

Decisive answered 11/10, 2019 at 19:48 Comment(0)
D
0

Okay, I got this figured out. Add a unique (not class="select2") class to all the Select2 dropdowns you have in modals, and then use this code:

// If a Modal is hidden, close any open Select2 contained therein - so it doesn't lag behind
$(document).on('hide.bs.modal', '.modal', function() {
   $(".select2-close").select2("close");
}); 

That seems to work well. (In this case I made a class called select2-close )

Decisive answered 11/10, 2019 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.