简体   繁体   中英

How to find the id of the active Select2 element

I have a form with multiple select menus generated with Select2 (version 4) where the id value of each select element is set dynamically. I'd like to find the id of the select element the user clicks on.

I can get this to work

$('.js-example-tokenizer-ajax-data').on('select2:open', function (evt) {
        myValue = $(this).attr('id');
 });

But I need to use myValue as a parameter for data inside an ajax call so an option getting the id of the active select2 element is needed. I've seen posts that suggest var selectedEle = $(document.activeElement) but I don't know how to get the id from there.

UPDATE

It seems I can include this as the value for the data parameter

data: getSelectedElement(function() {
            return JSON.stringify({variable: myValue})
        }),

with the function as

function getSelectedElement(callback) {
        $('.js-example-tokenizer-ajax-data').on('select2:opening', function (evt) {
            myValue = $(this).attr('id');
            callback();
        });
    }

But there are still some timing issues since the ajax seems to fire before a select element is clicked since when I load the page I get an error 'NoneType' object has no attribute '__getitem__' I gather since there was no value for myValue when the page loaded.

Are there other options to get the id of the selected select2 element? Alternatively, are there ways to sort out the timing issue?

If var selectedEle = $(document.activeElement) does in fact get the element that you want you can simply do document.activeElement.id .

Update based on poster's update:

In a different stack overflow answer someone said this.context will give you the correct element, in which case this.context.id would give you the id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM