问题
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?
回答1:
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 )
来源:https://stackoverflow.com/questions/58347627/close-any-select2-dropdowns-via-jquery