close select2 dropdown via javascript/jquery

2020-07-02 09:26发布

问题:

Good day, How can I properly close a select2 dropdown via jquery or javascript??

for now Im using select2-dropdown.toggle() to close it,

but I noticed that It will simply hide the list and the select2 box is still being highlighted

I want to lost focus it or something like that just to close it properly and be able to come up with a result like this one .

by the way the screen shots are dark because those select2 boxes are under a bootstrap modal that would come up whenever I press enter.

Any advice would really be appreciated! Thanks in advance

回答1:

I know this is an old question but in order to do this using the API you would simply do the following:

Select2 API

 $("#select2-drop-mask").select2("close");

The question also mentions bootstraps modal dialog which tends to be a reason why people want to close it programmatically.

For anyone's info this is how you do that:

Bootstrap 3

$('#myModal').on('hidden.bs.modal', function () {
  $('#select2-drop-mask').select2("close");
})

Bootstrap 2

$('#myModal').on('hidden', function () {
   $('#select2-drop-mask').select2("close");
})


回答2:

In v4.0, none of the other answers worked for me. Using jQuery to select just the mask had no effect. I had to use the id of the select box itself:

$("#mySelectElement").select2("close")

This also worked, but may not be preferred:

$("#mySelectElement").select2().trigger("select2:close");

Documentation

Also, for Bootstrap 3, the hidden.bs.modal event was too late and the select2 mask would linger for a second during the animation. The hide.bs.modal worked a little smoother for us:

$('#modalYourModal').on('hide.bs.modal', function () {
    //close select2 in case its open
    $("#mySelectElement").select2("close");
});


回答3:

this one works for me $("#select2-drop-mask").click();



回答4:

The select2-dropdown-*mask* didn't work for me, but the below did.

$('#select2-drop').select2('close');


回答5:

select2-dropdown.blur();

I think this is what you're looking for. Here you have an example in JSFiddle created by me just now.