Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close select2 dropdown via javascript/jquery

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 enter image description here

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 enter image description here.

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

like image 820
melvnberd Avatar asked Feb 08 '14 16:02

melvnberd


People also ask

How do I select a Dropdownlist using jQuery?

if your options have a value, you can do this: $('select'). val("the-value-of-the-option-you-want-to-select"); 'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

How do I stop select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

How do you focus Select 2?

$('#id'). select2('open'); will set focus and open the select2 ready for search. $('#id'). select2('focus'); will set the focus on select2 but not select2 will be not opened for search.


2 Answers

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");
})
like image 181
hutchonoid Avatar answered Oct 19 '22 16:10

hutchonoid


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");
});
like image 25
shanabus Avatar answered Oct 19 '22 16:10

shanabus