Select2 load data using ajax cannot select any option

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 use ASP MVC 4. The select command receives data using ajax and displays the parameters, but these parameters are not available for selection. While reading other posts, they describe the use of the id function, but this function clearly disappears in the select2 version that I am using 2.4

I follow the ajax example in the documentation showing on github "Downloading remote data"

+14
javascript jquery ajax jquery-select2 jquery-select2-4
Mar 13 '15 at 15:09
source share
1 answer

If your ajax response does not contain id attributes and text , you should fix them on the client side

This is a requirement for version 4.0 (I 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 } }; } } 
+57
Mar 16 '15 at 16:37
source share



All Articles