select2 load data using ajax cannot select any option
Asked Answered
O

2

17

I have the following code (javascript):

$('#cbxConnections').select2({
    minimumInputLength: 0,
    multiple: false,
    allowClear: true,
    placeholder:{
        text:"@Diccionario.Connections",
        id:" @Diccionario.Connections"
    },
    ajax:{
        url:'@Url.Action("GetActiveConnections","Admin")',
        dataType: 'json',
        type:'post',
        data:function(params){
            return {
                q: params.term
            };
        },
        processResults: function(data,page){
            return {
                results: data
            };
        }
    },
    escapeMarkup: function (markup) { 
        return markup; 
    },
    templateResult: function(response){
        return '<div>'+response.Name+'</div>';
    },
    templateSelection: function(response){
        return response.Id;
    },
    id: function(connection){
       console.log(connection);
    }
});

For the server side I am using ASP MVC 4. The select get data using ajax and render the options but this options are not selectable. Reading other posts, they describe using the id function, but this function appearently desappears on the version of select2 I'm using 2.4

I'm following the example of ajax on the documentation showing on github "Loading remote data"

Orchidectomy answered 13/3, 2015 at 15:9 Comment(1)
Possible duplicate of Unable to select a result from the select2 search resultsRosco
M
70

If your ajax response doesn't have id and text attributes you should fix them client side

This is a requirement on version 4.0 (don't know why)

ajax: {

   processResults: function (data, params) {

                params.page = params.page || 1;

                // you should map the id and text attributes on version 4.0

                var select2Data = $.map(data.result.data, function (obj) {
                    obj.id = obj._id.$id;
                    obj.text = obj.name;

                    return obj;
                });

                return {
                    results: select2Data,
                    pagination: {
                        more: data.result.more
                    }
                };
            }

 }
Malformation answered 16/3, 2015 at 16:37 Comment(3)
Thanks ! helped a lot.Billiebilling
Thanks for your explanation.Deadeye
Perfect as I wanted. Thanks a lot.Artemus
R
0

I had a problem that I could not unselect option (it was a select multiple) and the problem was that I passed id as an number, but it should be string

var select2Data = $.map(data.result.data, function (obj) {
    obj.id = '' + obj._id.$id; //small fix
    obj.text = obj.name;

    return obj;
});
Readjustment answered 25/8, 2022 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.