I am also using select2 and ajax API for generating dynamic options. Everything works except the selected value is not previewed when we refresh the page.
I tried trigger (‘change’) but didn’t work instead, it stuck to loop and got “Maximum call stack size exceeded” error.
onReady: function() {
this.control_select = this.$el.find('.post-select');
this.save_input = this.$el.find('.post-select-save-value');
this.control_select.select2({
ajax: {
url:'https://thingproxy.freeboard.io/fetch/https://symbol-search.tradingview.com/symbol_search/?exchange=&type=&hl=true&lang=en&domain=production',
dataType: 'json',
events: {
change: () => this.saveValue(),
keyup: () => this.saveValue()
},
data: function (params) {
return {
text: params.term,
};
},
processResults: function (data) {
//console.log(data);
const myObj = data;
let symb = [];
let obj = {};
myArray = []; // making empty array before returning new values
for(let x in myObj){
myArray.push({
id: x,
text: myObj[x].exchange+':'+myObj[x].symbol.replace(/<\/?[^>]+>/gi, ''),
symbol: myObj[x].exchange+'-'+myObj[x].symbol.replace(/<\/?[^>]+>/gi, '')
});
};
return {
results: myArray,
}
},
},
});
this.control_select.change(() => {
this.saveValue();
})
},
saveValue: function() {
let index = this.control_select.val();
this.setValue(myArray[index]);
},
onBeforeDestroy: function() {
this.saveValue();
}