select2 load data using ajax cannot select any option - javascript

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"

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
}
};
}
}

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;
});

Related

Change remote url based on search query

I have a select2 field which is retrieving data from a remote api. I can get that working. What I'm trying to do is change the remote url based on what the user has typed. If the first two letters typed are for example "AA" then search using a url and when the first two characters are "88" then search using another url.
This is my code so far:
this.selector.select2({
minimumInputLength: 2,
ajax: {
url: function(param){return 'http://localhost:3000/suggestions?&'},
dataType: 'json' ,
data: function (params) {
var query = {
search: params.term,
}
return query;
},
processResults: function(data) {
var results = [];
$.each(data, function (index, search) {
results.push({
id: search.id,
text: search.val
});
});
return {
"results":results
};
},
},
width: 'resolve',
});
I've looked but can't find an event which is fired when typing(searching).
According to docs the params argument passed to url callback is the same as in data callback. So you can rewrite your code as:
this.selector.select2({
minimumInputLength: 2,
ajax: {
url: function (params) {
var firstTwoLetters = params.term.slice(0, 2);
if (firstTwoLetters == '88') {
return 'some url';
} else if (firstTwoLetters == 'AA') {
return 'another url'
} else {
return 'http://localhost:3000/suggestions?&'
}
},
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
}
return query;
},
processResults: function (data) {
var results = [];
$.each(data, function (index, search) {
results.push({
id: search.id,
text: search.val
});
});
return {
"results": results
};
},
},
width: 'resolve',
});
I hope I understood your last request correctly.
The oninput event occurs as you type.
note: I'd rather comment it and not use Answer, however, I have less than 50 rep.

jQuery.map() to Parse results from select2 ajax call

I have the following select2 ajax call. How do I use the jquery $.map() to parse the returned json results. From the users array i need to get the Text and Value results. From the pager array I need to get the TotalItemCount. What I have below doesnt seem to work i.e the search results don't seem to display in the select list. No console errors are shown either so I'm not sure what Im doing wrong.
var url = '#Url.Action("GetEmployees", "Employees")';
var pageSize = 20;
$(".js-data-example-ajax").select2({
ajax: {
url: url,
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data, function (users) {
return {
text: users.Text,
id: users.Value
}
}),
pagination: {
more: (params.page * pageSize) < data.pager.TotalItemCount
}
};
},
cache: true
},
minimumInputLength: 2,
placeholder: "-- Select --",
allowClear: true
});
The json returned is as follows:
{
"pager":{
"PageCount":1,
"TotalItemCount":1,
"PageNumber":1,
"PageSize":20,
"HasPreviousPage":false,
"HasNextPage":false,
"IsFirstPage":true,
"IsLastPage":true,
"FirstItemOnPage":1,
"LastItemOnPage":1
},
"users":[
{
"Disabled":false,
"Group":null,
"Selected":false,
"Text":"Joe Blogs",
"Value":"97306aa4-d423-4770-9b45-87a701146b10"
}
]
}
I was correct. I wasn't using the jQuery.map() correctly. It should be as follows:
results: $.map(data.users, function (users) {
return {
text: users.Text,
id: users.Value
}
}),

Unable to select result from select2 dropdown

I have the following javascript/jQuery that pulls in data from via AJAX. That works fine however I can cannot seem to be able to select an option from the dropdown? Can anyone explain what I have done wrong..
This is something to do with the id..
$(".js-data-example-ajax").select2({
ajax: {
url: "/admin/generator/teams",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
id: function(data){ return data._id; },
});
First you should make sure processResults function returns an array of objects with id and text properties like this:
{ id: '1', text: 'Option 1' }
Then once the options are loaded, you can set the value by calling:
$(".js-data-example-ajax").val('1').trigger('change');

select2JS Ajax Option Value

I'm developing a form with select2JS.
In my first step I use a simple Select2
$(this).select2();
But I want to change it for an Ajax version.
$(this).select2({
multiple:multival,
ajax:
{
url: '/api/v2/vocabulary/'+vocabulary+'/words/list',
headers: {'X-AUTHORIZATION-TOKEN': token},
dataType: 'json',
type: "POST",
quietMillis: 100,
data: function (params) { // Lors d'une recherche
return {
pattern: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.words,
pagination: {
more: (params.page * 15) < data.total
}
};
},
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
cache: true
},
escapeMarkup: function (markup) {return markup; }, // let our custom formatter work
minimumInputLength: 0,
templateResult: function formatRepo (repo)
{
return repo.name;
},
templateSelection: function formatRepoSelection (repo)
{
return repo.name;
}
});
In the first version, my Ajax return the name of the Option ( When I send the form). In the Ajax version, the script create a new Option inside the select ( But not visible ) and when I send the form its an Id who is sent. Because in the Value of the new Option, its the Id and not the name.
I use Select2 4.0.1 and I find in the 3162' Line :
if (data.id) {
option.value = data.id;
}
I tried to change data.id by data.name, but it was not effective.
Do you have an idea?

cannot call val() if initSelection() is not defined error in select2 plugin

I am using select2 plugin to load remote data. I am using an aspx page which returns JSON data and same is assigned to select2 plugin. After user selects some value from the select2 textbox, i am forcing page to postback. After the postback i am using following code to reload to set the text in the select2 textbox.
var data = { "PatientID": "XYX", "Email": "testing#gmail.com" };
$('#e6').select2('val', '123');
But system is throwing following error: cannot call val() if initSelection() is not defined
Even if I define init, I am not able to set the value. I am using following code. Please help me set the value on the select2 textbox after the postback.
$(document).ready(function () {
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "data.aspx",
dataType: 'json',
quietMillis: 1000,
data: function (term, page) {
return {
name: term
};
},
initSelection: function (element, callback) {
var data = { "PatientID": "XYX", "Email": "testing#gmail.com" };
callback(data);
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
results.push({
id: item['Email'],
text: item['PatientID']
});
});
return {
results: results
};
},
},
});
});
window.onload = function () {
var data = { "PatientID": "XYX", "Email": "testing#gmail.com" };
//When this is called system is throwing error
//This code is required to show the value in select2 textbox after the post back
$('#e6').select2('val', data);
}
$(document).ready(function () {
$("#e6").on("select2-selecting", function (e) {
//alert("selecting val=" + e.val + " choice=" + JSON.stringify(e.choice));
var id = document.getElementById('<%= savebtn.ClientID %>');
document.getElementById('<%= hdnFld.ClientID %>').value = e.val;
id.value = e.val;
//causes post back
id.click();
});
});
There is a mistake with your script. I had the same problem and I saw your question. After I read the API docs of Select2 I realised my error.
You should place the initSelection at the same level as ajax. e.g.
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
initSelection: function (element, callback) {
var data = { "PatientID": "XYX", "Email": "testing#gmail.com" };
callback(data);
},
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "data.aspx",
dataType: 'json',
quietMillis: 1000,
data: function (term, page) {
return {
name: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
results.push({
id: item['Email'],
text: item['PatientID']
});
});
return {
results: results
};
},
},
});

Categories

Resources