I'm generating a table of results dynamically and one cell in each row contains an autocomplete. I'm using Select2 to display the autocomplete options and am populating the drop-down from ajax data and custom data unique for each row. My ajax data is coming from my Python app method and I'm using POST to send a variable back to the Python method to use to generate the custom data. Here's how this is set-up:
$(".js-example-tokenizer-ajax-data").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
},
placeholder: 'Select an option',
maximumSelectionLength: 3,
ajax: {
url: '{{ url_for("select2Autocomplete") }}',
contentType: 'application/json',
method: "POST",
dataType : 'json',
data: JSON.stringify({variable:myValue}),
processResults: function (data) {
return {
results: data.resource_list
};
}
}
});
I've set the id of the select element to a value from my Jinja template.
<select onfocus="this.selectedIndex = -1;" id="{{ key }}" class="js-example-tokenizer-ajax-data" multiple="multiple" miriamId="{{ value }}" style="width:100%">
<option value="{{ key }}" selected>{{ miriam_name_dict[value] }}</option>
</select>
Since it's dynamic I don't know what that id is for each select. I am able to get the value like this:
$('.js-example-tokenizer-ajax-data').on('select2:opening', function (evt) {
myValue = document.getElementById(this.id).getAttribute('id');
console.log("myValue: ", myValue)
});
I'd like to use myValue as the variable I send back to my python method via the data variable. Is there some way to access myValue to use in the autocomplete code?
I was able to pass back data to the autocomplete method for the select element the user clicked on as follows:
$(".js-example-tokenizer-ajax-data").select2({
tags: true, //Allows for free text input of tag values
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
},
placeholder: 'Select an option',
maximumSelectionLength: 3,
ajax: {
url: '{{ url_for("select2Autocomplete") }}',
contentType: 'application/json',
method: "POST",
dataType : 'json',
data: function() {
var myValue = $(this).attr('id');
return JSON.stringify({variable: myValue})
},
processResults: function (data) {
return {
results: data.resource_list
};
}
}
});
I was not able to use {variable: $(this).attr('id')} directly as the value for the data parameter and did need to use JSON.stringify on the value to get the value in the python method using jsonData = request.json["variable"]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments