Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 option templateResult not being called

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.com/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.

like image 983
xylar Avatar asked Dec 13 '22 12:12

xylar


1 Answers

I 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.com/img.png" /> ' + data.text + '</span>';
    }
});
like image 51
xylar Avatar answered Dec 17 '22 22:12

xylar