Select2 Ajax Method Not Selecting
After looking at another answer it would seem I need to also pass id field with every call, otherwise it will disable the input.
Sample code that fixed it:
$('.select2').select2({
placeholder: "Policy Name",
minimumInputLength: 3,
multiple: false,
quietMillis: 100,
id: function(bond){ return bond._id; },
ajax: {
url: "http://localhost:3000/search",
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
search: term,
page: page || 1
}
},
results: function(bond, page) {
return {results: bond.results, more: (bond.results && bond.results.length == 10 ? true: false)}
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: initSelection
})
Edit
Since this keeps getting upvoted I'll elaborate a bit. The .select2() method expects a unique id
field on all results. Thankfully, there's a workaround. The id
option accepts a function like this:
function( <INDIVIDUAL_RESULT> ) {
// Expects you to return a unique identifier.
// Ideally this should be from the results of the $.ajax() call.
}
Since my unique identifier was <RESULT>._id
, I simply return <RESULT>._id;
Also be careful with the case. I was using Id
but select2 expects id
. Could save someone's time.
Like Dropped.on.Caprica said: Every result item needs an unique id.
So just assign every result id
an unique number:
$('#searchDriver').select2({
ajax: {
dataType: 'json',
delay: 250,
cache: true,
url: '/users/search',
processResults: function (data, params) {
//data is an array of results
data.forEach(function (d, i) {
//Just assign a unique number or your own unique id
d.id = i; // or e.id = e.userId;
})
return {
results: data
};
},
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
The thing is that the JSON data need a property called "id". There's no need for
id: function(bond){ return bond._id; }
If the data does not have an id for itself, you can add it with a function on processResults like here.
$(YOUR FIELD).select2({
placeholder: "Start typing...",
ajax: {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YOUR API ENDPOINT",
dataType: 'json',
data:
function (params) {
return JSON.stringify({ username: params.term });
},
processResults: function (data, page) {
var results = [];
$.each(JSON.parse(data.d), function (i, v) {
var o = {};
o.id = v.key;
o.name = v.displayName;
o.value = v.key;
results.push(o);
})
return {
results: results
};
},
cache: true
},
escapeMarkup: function (markup) { return markup;},
minimumInputLength: 1,
templateResult: function (people) {
if (people.loading)
return people.text;
var markup = '<option value="' + people.value + '">' + people.name + '</option>';
return markup;
},
templateSelection: function (people) { return people.value || people.text }
});