Close ANY Select2 dropdowns via jQuery

萝らか妹 提交于 2020-01-06 06:10:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!