I have a select2 which is defined with minimum input length and ajax call (remote data) to retrieve data from server based on user input.
$('#itemList').select2({
minimumInputLength: 3,
ajax: {
// AJAX configuration here
}
});
When a user selecting a previously saved record to update, I need to set the option programmatically so the user can see it and if needed, can change. I have tried setting the value and also appending as a new option, but nothing seems to work.
Attempt 1 :
$('#itemList').val(value).trigger('change');
Attempt 2:
var option = new Option(text, value, true, true);
$("#itemList").append(option).trigger('change');
Also tried this
Attempt 3:
$.ajax({
url: link,
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: false,
processData: false,
cache: false
}).then(function (data) {
// create the option and append to Select2
var option = new Option(text, value, true, true);
$("#itemList").append(option).trigger('change');
// manually trigger the `select2:select` event
$("#itemList").trigger({
type: 'select2:select',
params: {
data: data
}
});
});
Nothing seems to work.
Any help would be highly appreciated! Thank you in advance.