I have select2 v4.0.0 populated from an Ajax array. If I installed val select2, I can see, using javascript debugging, that it has selected the correct item (# 3 in my case), however this is not shown in the select box, it still shows placeholder. 
While I should see 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 selected item and not placeholder in the selection box? Should I post this as part of an AJAX JSON response, perhaps?
In the past, Select2 required the initSelection parameter, which was defined whenever a custom data source was used, allowing you to determine the initial selection for the component. This worked fine for me in version 3.5.
jquery-select2-4
Greg May 19 '15 at 4:07 2015-05-19 04:07
source share