I'm trying to get select2 working with multiple pre-selected options. I'm using it to let users choose several options then have them saved to then be able to come back and edit them. however I can't get the select2 initSelection to work correctly to populate the existing options the user has already chosen. here is the code i have tried using with alerts to show when something has fired however the alert("done"); has never fired yet and the alert($(element).val(0) fires twice. once with the value in the input and then again with a blank.
<input type="text" id="Commissioners" name="Commissioners" value="test" />
$("#Commissioners").select2({
placeholder: 'Select Commissioners',
minimumInputLength: 2,
allowClear: true,
multiple: true,
width: 'resolve',
ajax: {
url: "/Commissioner/CommissionerAutoComplete/",
dataType: 'json',
data: function (term, page) {
return {
search: term // search term
};
},
results: function (data) {
return { results: data };
}
},
initSelection: function (element, callback) {
// the input tag has a value attribute preloaded that points to a preselected make's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the make text is shown preselected
alert($(element).val());
$.ajax({
url: "/UserProfile/LoadServiceTypeAndCommissioners",
type: "GET",
dataType: "json",
data: { UserId: '@Model.UserID', serviceTypeId: id}
}).done(function (data) {
alert("done");
callback(data.results);
});
},
formatResult: s2FormatResult,
formatSelection: s2FormatSelection
}).select2('val', []);
I figured out that the second alert fires for the .select2('val', []); at the end. however removing this causes the placeholder to not work and adding in a value here like ["1"] does not result in a selected item