I see this has been asked couple of times here, but none of them work for me. So i'm positing it again to see if someone faced something like this. I have a select2 inside a Model, and was able to populate it by making an ajax call to the Api. It works like a charm until here, problem is i'm not able to select any value into the 'Code'. Below is my code for the ajax and html
/HTML/
<div class="col-lg-8 col-sm-7">
<input id="procedureSelect" name="SelectProcedure" class="form-control">
</div>
/*Ajax Call */
$('#procedureSelect').select2({
placeholder: 'Select Procedure',
allowClear: true,
quietMillis: 1000,
ajax: {
url: '#Url.Action("GetProcedures", "Procedure")',
dataType: 'json',
data: function (term, page) {
return {
searchTerm: term,
page: page
};
},
results: function (data, page) {
var more = (page * 25) < data.total;
return { results: data.procedureData, more: more };
}
},
formatResult: function (data) {
return '<div>' + data.procedure_code + " - " + data.short_description + '</div>';
},
formatSelection: function (data) {
var result = data.procedureData;
return result.procedure_code;
}
});
I finally figured out the answer, by doing some more research. The Thing is select2 expects a unique Id for the data returned. So o added below one line of code to my javascript to assign the Id
id: function (data) { return data.procedure_code; },
Now it works fine.
Related
I have a dropdown created with select2 (v4.0.13 and I can not change it) using AJAX requests on a form where the user can search for things. The page is built with Thymeleaf and when the view is reloaded the dropdown value is lost.
Following the recommendation of the documentation itself when you deal with AJAX values, I have writed this code:
let selectedOption = $('#select2-id');
$.ajax({
type: 'GET',
dataType: 'json',
url: baseAjaxUrl + '/api_endpoint?q=' + myVar,
}).then(function (data) {
if (data.length !== 0) {
let optionValues = data[0];
let option = new Option(optionValues.name, optionValues.id, true, true);
selectedOption.append(option).trigger('change.select2');
selectedOption.trigger({
type: 'select2:select',
params: {data: optionValues}
});
}
});
Now, when the view is reloaded the dropdown has the value but does not show its text. An x appears to remove it and if you hover the mouse over it in the tooltip the text that should be displayed in the dropdown appears.
In the <span> generated by select2 I can see the title attribute with the value that should be displayed:
<span class="select2-selection__rendered" id="select2-anId-container" role="textbox" aria-readonly="true" title="The text that should be displayed">
<span class="select2-selection__clear" title="Remove all items" data-select2-id="20">×</span>
</span>
The select2 is initialised as follows:
$('#select2-id').select2({
ajax: {
url: baseAjaxUrl + '/api_endpoint',
dataType: 'json',
delay: 180,
data: function (parameters) {
return {
q: parameters.term,
page: parameters.page
};
},
processResults: function (data, page) {
return {
results: data
};
}
},
placeholder: {
id: "-1",
text: "Select an item"
},
allowClear: true,
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 5,
templateResult: formatItem,
templateSelection: formatItemSelection,
theme: "bootstrap",
width: myCustomWidth
});
What is the problem or what have I done wrong?
Greetings.
After finding this answer, my problem was that when selecting an option, templateSelection is used. Checking the function I realised that the object I receive has the fields id and name. The object that handles select2 also has the fields id and name but it has another one, text, and this is the one it uses to show the value!
So in the function I use for templateSelection I have to do:
if (data.text === "") {
data.text = data.name;
}
... other stuff ...
return data.text;
Done!
I'm using Select2 4.0.6-rc.0 from Jquery, the thing is that when I copy and paste a value to be searched and there is only one option, that option is disabled and I can select it nor click it.
In this image I'm expecting only one results cause SF190 belongs to only one user.
But if the search brings more than one result everything is ok, like in this image:
This is the piece of code I'm using to initialize the Select2:
$('.js-data-example-ajax').select2({
width: '100%',
minimumInputLength: 1,
tags: [],
ajax: {
url: '<URL of my action>',
type: "POST",
dataType: "json",
delay: 1000,
data: function (term) {
return {
query: term.term
};
},
processResults: function (data) {
var res = data.map(function (item) {
return { id: item.Id, text: item.Id + ' ' + item.Name };
});
return {
results: res
};
}
}
});
I really don't know whats going on and I can't find any related solutions.
Here's a working codepen based on your example (and another codepen):
$( ".select2" ).select2({
ajax: {
url: "<url>",
dataType: 'json',
delay: 1000,
//type: "POST",
tags: [],
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
var res = data.map(function (item) {
return { id: item.id, text: item.text };
});
return {
results: res
};
},
},
minimumInputLength: 1
});
The only difference is that I removed the request type - I'm pretty sure that you are getting the data here, not posting it :) And if you try to put it back, the filter stops working, albeit in a different way (it returns the full list no matter what you put in the filter), so it might be the source of your problem here.
There is one more thing to consider - are you sure that there is no other code affecting your selectbox? Like something that applies to the .js-data-example-ajax, or any <span> with a single child (that's what a Select2 dropdown part is) etc.
I am using Select2 JS Version 4.0.0-rc.1 and having trouble loading suggestions with remote Ajax method.
Below are the markups and code
<select class="form-control input-sm" id="selFrame1" name="selFrame1">
<option> Select Frame </option>
</select>
the JavaScript Jquery
$('#selFrame1').select2({
ajax: {
url: siteUrl+"suggest/frames",
dataType: 'json',
delay: 250,
method:'POST',
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// 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
return {
results: data.result
};
},
cache: true
}
});
The Json Result returned by server
{results: [{"Code":"123360000"},{"Code":"123360358"},{"Code":"123364000"},{"Code":"123400000"}], more: false }
I am totally not sure if I need to write specific functions to show suggestions, the comments on the Ajax section say that we should not alter the result Json data.
Now somebody please tell me what more I should to get the code working to show the suggestions.
I guess with the new version of select2 a lot of stuffs have changed.
Your response is being returned as a Select2 3.x response, which is fine. We've provided the processResults method because of this (previously results) so you can modify the response on the client side.
In your case, your response includes the results key but your processResponse function is referencing a result key which does not exist. If you change it to something like
processResults: function (data, page) {
// 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
return {
results: data.results,
pagination: {
more: data.more
}
};
},
Then things should start working. This also maps the existing more property on the response to the new pagination key that we migrated to in Select2 4.0.
Your Json response has to be like this :
{
"total_count":2,
"items": [
{"id":"01", "name":"item 1"},
{"id":"02", "name":"item 2"}
]
}
To work, you an id property.
Here is my config :
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'><div class='select2-result-repository__img'><img src='" + repo.img + "' width='80' height='80' /></div><div class='select2-result-repository__meta'><div class='select2-result-repository__title'>" + repo.full_name + "</div>";
markup += "<div class='select2-result-repository__statistics'><div class='select2-result-repository__type'><i class='fa fa-flash'></i> Type : " + repo.type + "</div><div class='select2-result-repository__usecase'><i class='fa fa-eye'></i> Use case : " + repo.usecase + "</div></div></div></div>";
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name;
}
// Init select2
$(".select2").select2({
ajax: {
type : "GET",
url : "{{ path('tag_search_js') }}",
dataType: 'json',
delay : 250,
data : function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
placeholder: "Select a tag",
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
Hope this helps !
I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.
Here is my script:
$("#sub_lessons").select2({
maximumSelectionSize: 1,
placeholder: "Select Sublessons",
allowClear: true,
multiple:true,
ajax: {
url: "getData.action?lid="+lessonid,
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
My html snippet:
<input type="hidden" id="sub_lessons" style="width:300px"/>
When we clicking on the select2 box the data is loading perfectly,
but I have the function like setValue() when button is clicked.
<input type="button" onclick="setValue(1)"/>
And my function is:
function setValue(no)
{
$('#sub_lessons').select2('val',no);
}
But the value is not being set. I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.
any help would be appreciated.
try something like this
$('#sub_lessons').select2('val','no');
I try this; work for me. You should add this to initSelection select2:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#sub_lessons').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.