Hi guys,
I am really struggling to get my ajax-sourced select2 with pre-selected values to work. My case is that I have three on my site, and they share the same class name. Therefore I’m making a loop and for each one, trying to instantiate a select2 object. But for some reason I just cannot get it to work. I can see the values when entering the field, and there are an empty preselected value, which should be selected. I tried to follow https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
My HTML:
<div class="form-group">
<select class="product-select form-control" name="products[]" multiple="multiple" id="MSK"
</select>
</div>
<div class="form-group">
<select class="product-select form-control" name="products[]" multiple="multiple" id="SLG"></select>
</div>
<div class="form-group">
<select class="product-select form-control" name="products[]" multiple="multiple" id="ASC"></select>
</div>
And Jquery;
$(’.product-select’).each(function(){
$(this).select2({
ajax: {
dataType: 'json',
url: 'products/'+$(this).attr('id')
}
});
// Fetch the preselected item, and add to the control
var prdSelect = $(this);
$.ajax({
type: 'GET',
url: 'products/user/'+$(this).attr('id')
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.name, data.id, true, true);
prdSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
prdSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
});
You can see it in action on: http://resupply.resmedmaribo.dk/public/users/new/44
Hope you can help me!