Retrieve options on open

Hi. I’d like to know if there is a way to retrieve the select2 options (all, not just selected) when “open” event is triggered, please?

I am trying to avoid calling ajax call programatically as I know it is called when select is opened, right?

I was looking in the https://select2.org/programmatic-control/events, but couldn’t find anything useful. Can anyone help, please?

Thank you.

As long as you’re not using a remote AJAX data source, all of the <option>s in the Select2 will be present in the DOM as soon as the Select2 widget is initialized. You don’t need to wait for the dropdown to be opened. But if you want to, just listen for the “select2:open” event and in your event handler do something like $('#my-select > option'). That will return an array of jQuery-wrapped <option>s in the Select2. (But you can actually execute that code any time after the Select2 is initialized and you’ll get the same results.)

And a correction to what you wrote aboe: the AJAX call is not made when the Select2 is opened, it’s made when the user types in the Select2’s search field. And even then, the data returned from the AJAX call is not immediately converted into <option> elements in the DOM; for AJAX data sources, Select2 only adds <option> elements into the DOM when the user selects an item from the dropdown.