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
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.
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.
$('#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.
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");
})
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With