How do I detect which element the .select2-container was visually attached to?

So, let’s say that there are 4-5 select elements in my HTML, and that I need to detect the ID of the element for which .select2-container has been created and opened.

If users clicks on their elements, I can do something like this:

<select id="first-select">
  <option value="1">1-1</option>
  <option value="2">1-2</option>
  <option value="3">1-3</option>
</select>
<select id="second-select">
  <option value="1">2-1</option>
  <option value="2">2-2</option>
  <option value="3">2-3</option>
</select>
<select id="third-select">
  <option value="1">3-1</option>
  <option value="2">3-2</option>
  <option value="3">3-3</option>
</select>

<div style="display:none">
  <input type="hidden" name="elemID" id="elemID" value="">
</div>

And then, in my scripts, I have this.

$(document).on('click',function(event){
    var targ = event.target.id;
    if(targ) {
        $('#elemID').val(targ);
    }
});

$('body').on('keyup','.select2-search__field',function(){
    var elem = $('#elemID').val();
    var startParam = "select2-";
    var endParam = "-container";
    var startIndex = elem.indexOf(startParam);
    var endIndex = elem.indexOf(endParam);
    if(startIndex>=0 && endIndex) {
        elem = elem.replace(startParam,'').replace(endParam,'');
        console.log(elem);
    }
});

This is all fine and dandy, if the user uses clicks to navigate from one element to another. However, if the user uses the keyboard (TAB, or SHIFT + TAB) to navigate from one element to another, my little tricks fail, and the hidden elemID is left empty (or worse, stuck with the wrong ID).

How do I detect which element the .select2-container was visually attached to? Or, to put it a bit differently, how can I detect which of my selects was the trigger for creation and showing of .select2-container?

You don’t need any of that complicated element detection hackery :slight_smile:. The “select2:opening” and “select2:open” events point to the underlying HTML select element associated to the triggered Select2 in their target property (even when the event listener is attached to an ancestor element such as body). So just register a handler for one of those events on the document body and in the event handler, reference event.target to see which HTML select is involved.