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?
Aucun commentaire:
Enregistrer un commentaire