I would like to use templateResult option to format my results using select2 v4. I have the following code:
$(".search").select2({
minimumInputLength: 3,
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data.items
};
},
templateResult: function (data) {
console.log('templateResult');
return '<span><img src="//example/img.png" /> ' + data.text + '</span>';
},
}
});
However, templateResult
doesn't appear to be getting called as nothing is outputted to the console. Even if I change the return to 'TEST', the default results are still displayed. The code works the same whether I include the templateResult or not.
I would like to use templateResult option to format my results using select2 v4. I have the following code:
$(".search").select2({
minimumInputLength: 3,
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data.items
};
},
templateResult: function (data) {
console.log('templateResult');
return '<span><img src="//example./img.png" /> ' + data.text + '</span>';
},
}
});
However, templateResult
doesn't appear to be getting called as nothing is outputted to the console. Even if I change the return to 'TEST', the default results are still displayed. The code works the same whether I include the templateResult or not.
- 1 Odd - it seems to work fine here: jsfiddle/RoryMcCrossan/waxt54cv. – Rory McCrossan Commented Feb 27, 2019 at 13:55
- Thanks - that's without the ajax call but it helped me spot the issue. The templateResult option was inside the ajax callback. – xylar Commented Feb 27, 2019 at 14:09
- Ahh yes! I missed that myself. Glad you got it working – Rory McCrossan Commented Feb 27, 2019 at 14:11
2 Answers
Reset to default 16I had the templateResult inside ajax scope. Fix is below:
$(".search").select2({
minimumInputLength: 3,
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data.items
};
},
},
templateResult: function (data) {
console.log('templateResult');
return '<span><img src="//example./img.png" /> ' + data.text + '</span>';
}
});
Check your processResults - results: data.items
, I switched to data.results