I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder.
Whereas I should be seeing something like this:
In my form fields:
<input name="creditor_id" type="hidden" value="3" />
<div class="form-group minimal form-gap-after">
<span class="col-xs-3 control-label minimal">
<label for="Creditor:">Creditor:</label>
</span>
<div class="col-xs-9">
<div class="input-group col-xs-8 pull-left select2-bootstrap-prepend">
<select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
<option></option>
</select>
</div>
</div>
</div>
My javascript:
var initial_creditor_id="3";
$(".creditor_select2").select2({
ajax: {
url: "/admin/api/transactions/creditorlist",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
c_id: initial_creditor_id,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
placeholder: "Search for a Creditor",
width: "element",
theme: "bootstrap",
allowClear: true
}).on("select2:select", function (e) {
var selected=e.params.data;
if (typeof selected!=="undefined") {
$("[name='creditor_id']").val(selected.creditor_id);
$("#allocationsDiv").hide();
$("[name='amount_cash']").val("");
$("[name='amount_cheque']").val("");
$("[name='amount_direct']").val("");
$("[name='amount_creditcard']").val("");
}
}).on("select2:unselecting", function (e) {
$("form").each(function () {
this.reset()
});
("#allocationsDiv").hide();
$("[name='creditor_id']").val("");
}).val(initial_creditor_id);
How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?
In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.