I'm new to jQuery and Javascript so maybe someone can help me out? I used .select2 to get this result but I'm not able to select and item. Here is the code
JAVASCRIPT
$("#namesCombobox").select2({
placeholder: "Search for a name",
minimumInputLength: 3,
ajax: {
url: "/api/machineparkcustomers/getnamescontaining",
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
query: term,
};
},
results: function (data, page) {
return {
results: data
};
},
cache: true
},
formatResult: function (state) {
return state;
}
});
HTML:
<input type="text" id="namesCombobox" class="col-sm-12" />
You don't show what the data looks like that your ajax request returns, but judging by your formatSelection
function and the behavior you are experiencing, I am guessing that the data is an array of strings. What it should be is an array of objects, where each object has an id
property and a text
property.
This jsfiddle shows the problem.
Try changing the ajax results
function to this:
results: function(data) {
return { results: $.map(data, function(state) {
return { id: state, text: state }
}) };
}
You will also have to remove the formatResult
function.
Found this question while searching for a solution to a similar problem The accepted answer is great, but not my issue.
Select2 provides a callback "id" function that it will invoke to determine the ID you'd like to use for each result in the data. For my case my "id" function was not correct.
this.el.select2({
minimumInputLength: 12,
query: this.search.bind(self),
id: function (clinicianDto) { return clinicianDto.id(); },
formatResult: function (clinicianDto: any) {
return "<div class='row'><div class='col-sm-12' >" + clinicianDto.firstName() + ' ' + clinicianDto.lastName() + "</div></div>";
},
formatSelection: function (clinicianDto: any) {
return clinicianDto.firstName() + ' ' + clinicianDto.lastName();
},
initSelection: function (element, callback) {
if (self.selectedClinician) {
callback(self.selectedClinician.SerializeModel());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.