質問

I'm using select2 and in my site. I need to know at some point if the dropdown is open or closed. I've studied the documentation but I don't see how this can be done. For example, something like this would be nice:

if ($('select').select2('isOpen') === true) { ... }

Any suggestions?

役に立ちましたか?

解決 3

By doing some code inspection, it looks like select2-dropdown-open is the class that it adds. But there is an event select2-open in the documentation that fires when the dropdown is open. You can use that to set a variable, or perform an action (also select2-close).

You can do something like this:

$("#e11").on("select2-open", function() { 
    $(this).data("open", true);
});
$("#e11").on("select2-close", function() { 
    $(this).data("open", false);
});

if ($("#e11").data("open")) {
    //do something
}

2018 Edit

It appears that the names of the events have been updated since 2014. See user1636505's answer below.

他のヒント

In version 4.0 of select2 you can listen to select2:opening, select2:open, select2:closing and select2:close events on select element, for example:

$('select').on('select2:open', function (e) {
    // select2 is opened, handle event
});

Select2 4.0 has an isOpen method. If #mySelect is your HTML select element then:

$('#mySelect').data('select2').isOpen()

...will return true or false depending on the state of Select2.

As of Select2 4.0.6, this has been updated to the following

$("#foo").select2("isOpen")

This will return true/false

Hope this helps!

change is fired whenever an option is selected or removed.

select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented.

select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.

select2:select is fired whenever a result is selected. select2:selecting is fired before this and can be prevented.

select2:unselect is fired whenever a result is unselected. select2:unselecting is fired before this and can be prevented.

It's better to do this:

var select2 = $('#selectorname').data('select2');
if (select2.opened()) {
        //do it
    } else {
        //dont do it
    }

$('select').select2('isFocused');

https://github.com/select2/select2/issues/39

It works perfectly.

$(".select2-container").is(":visible")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top