formatSelection not working in select2.js - javascript

I am using select2.js to populate the field with multiple values using ajax call.
Below is the code that I am using.
HTML
<input id="id_test_name" class="form-control">
Script
<script type="text/javascript">
$("#id_test_name").select2({
placeholder: "Search for an Item",
minimumInputLength: 2,
ajax: {
url: "/resourse/?format=json&name=xyz",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
option: term
};
},
results: function (data, page) {
return {
results: $.map(data.results, function (item) {
return {
name: item.name,
abbreviation: item.abbreviation,
id: item.id
}
})
};
}
},
formatResult: function (data, term) {
return data.name + '(' + data.abbreviation +')';
},
formatSelection: function (data) {
return data.name + '(' + data.abbreviation +')';
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) {
return m;
}
});
</script>
results are populating in dropdown but I am not able to select the populated results, I am not able to find what I am doing wrong?
Also I need the id of selected results in some other(hidden) field.
Update:
jsfiddle: http://jsfiddle.net/n5phohov/2

If you are using the current select2 v4, the parameters formatResult and formatTemplate were replaced by templateResult and templateSelection. Also you can call functions to format the results. Look the example bellow, observe that I used base64 image contained in a data attribute, you can easily replace for an image link matching with the option.
$('#combo').select2({
language : "pt-BR",
allowClear: true,
placeholder: "Selecione",
templateResult: formatSingleResult,
templateSelection: formatSelected
}).on('select2:select', function (e) {
var data = e.params.data;
let thumbnailValue='';
$(data.element.attributes).each( function (){
if ($(this)[0].name == 'data-thumbnail' ){
thumbnailValue = $(this)[0].value;
}
});
function formatSelected(state) {
let img='';
if (printImage == true){
img='<img src="' + $(state.element).attr('data-thumbnail') +'" class="comboImg"/>';
}
$item = $(`<span>${img} ${state.text.trim()}<span>`);
return $item;
}
function formatSingleResult (result) {
if (!result.id) {
return result.text.trim();
}
let img="";
if (printImage == true){
img='<img src="' + $(result.element).attr('data-thumbnail') +'" class="flag"/>';
}
const optionText = result.text.trim();
const $item = $(`<span>${img} ${optionText}<span>`);
return $item;
}

Related

Select2 : How to get other response from ajax?

sorry for my bad english. I just wanna ask about select2 ajax, i have problem with this, i don't know how to get other response from my API.
So this is the response from my API.
enter image description here
so i want to get zip_code value when select2 has on changed. but i don't know to get it.
this my code..
$(".myselect").select2(
{
theme: "bootstrap4",
placeholder: "Provinsi, Kota/Kab, Kecamatan, Kelurahan",
minimumInputLength: 3,
ajax: {
url: url, //changing by env
dataType: 'json',
type: "GET",
delay: 150,
data: function (params) {
return {
filter: params.term
};
},
processResults: function (data, params) {
var res = data.data.locations.map(function (item) {
return {
id: item.id,
text: item.name,
zip: item.zip_code
};
});
return {
results: res
};
},
templateResult: function(result) {
return result.text;
},
templateSelection: function(selection) {
return selection.text;
}
},
}).on('change.select2', function(e){
console.log($(this).val(e.text));
villText = $("#village option:last-child").text();
var villVal = $("#village option:last-child").val();
// console.log($("#village option:last-child").val())
// var villVal1 = $("#village option:last-child").val();
villKel = villText;
villKel = villKel.split(',')[2];
$("#village_kel").val(villKel);
var villx = $('#village_land');
var vill_land = $("#village_land option:last-child").text();
vill_land_kel = vill_land;
vill_land_kel = vill_land_kel.split(',')[2];
$("#villageland_kel").val(vill_land_kel);
$('input[name="domisili"]').click(function() {
if ($(this).attr("value") == "1") {
if(villx.empty()) {
villx.append($('<option></option>').attr('value', villVal).text(villText));
villx.prop('selectedIndex', 0);
}
else {
villx.append($('<option></option>').attr('value', "").text(""));
}
}
})
});
picture below is the result when i get the text of value from my API.
enter image description here

Select2, Symfony: Autocomplete with remote data not working

I'm trying to implement an autocomplete search when searching for a city on my website (carpooling).
I made a controller searchCity which return a json with the cities:
/**
* #Route ("/city/{term}")
*/
public function searchCity($term)
{
$query = $this->getDoctrine()->getRepository('App:Ville')
->createQueryBuilder('v')
->select('v.id, v.nomReel AS text')
->where('v.nomSimple LIKE :term')
->setParameter('term', $term.'%')
->getQuery()
->getResult();
$query = array('results' => $query);
return new JsonResponse($query);
}
For exemple if I go to /city/Paris I'll get :
{"results":[
{"id":30438,"text":"Paris"},
{"id":29427,"text":"Paris-l\u0027H\u00f4pital"}, //I know single quotes
{"id":33294,"text":"Parisot"}, //don't work
{"id":33531,"text":"Parisot"}]}
select :
<div class="container">
<select id="citySelect" class="select2 select2-dropdown select2-search" name="term">
</select>
</div>
javascript :
$(document).ready(function(){
$("#citySelect").select2({
placeholder: "Select city",
ajax: {
dataType: "json",
url: function (params) {
return '/city/' + params.term;
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.ime, text: obj.ime };
})
};
}
}
});
});
When I search a city nothing shows up (searching ... and nothing)
with the console log I can see that data is there and well formated but the cities are not showing on the dropdown menu.
I think that my problem is with my javascript code and my comprehension of select2.
Regards
UPDATE :
js :
$(document).ready(function(){
$(".select2").select2({
placeholder: "Select city",
ajax: {
dataType: "json",
url: function (params) {
return '/city/' + params.term;
},
processResults: function (data) {
return {
results: data.results //return data directly
};
}
}
});
});
I guess when transforming data you wanted
return { id: obj.id, text: obj.text };
instead of
return { id: obj.ime, text: obj.ime };
Also looking at the json you posted you could probably (not tested) just do
processResults: function (data) {
return {
results: data.results;
};
}

set data attributes with ajax and select2

I'm trying setup data attributes into select2 options but without success, at this moment i have the following JS code
_properties.$localElement.select2({
ajax: {
url: "url",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
name: params.term, // search term
type: 1
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
cache: true
},
//define min input length
minimumInputLength: 3,
});
And i want setup a data-source for the selected option value.
I find the solution, looks that resultTemplate dont format the "visual" selected option , need to use templateSelection option:
templateSelection: function(container) {
$(container.element).attr("data-source", container.source);
return container.text;
}
I solved this problem.
$('select').on('select2:select', function (e) {
var data = e.params.data;
$("select option[value=" + data.id + "]").data('source', data.source);
$("select").trigger('change');
});
You can actually use the exact syntax, that you already used. The "source-attribute" just needs to be accessed via data().data.source of the specific select2-option.
So keep your processResults function like you did:
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
and if you want to retrieve the source of the selected option, you can do it like this:
var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;
In fact you can set any variable you want in your processResults function and then select it via data().data.variableName!

Jquery UI auto complete (with custom listing) not working

I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.

jQuery UI autocomplete- no results message

I'm trying to have a "No Results" message appear in the dropdown menu if there are no results. So for instance, if I type in "ABCD" into the text field, and there is no entity that matches, the message "No Results." will be displayed.
After looking through stackoverflow for the various different ways of accomplishing this, and trying a few of them, I still can't get it to work.
How can I add a "No Results" message to the dropdown menu when no results are found?
jQuery:
$element.autocomplete({
source: function (request, response) {
$.ajax({
url: thUrl + thQS,
type: "get",
dataType: "json",
cache: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12
},
success: function (data) {
response($.map(data, function (item) {
if (data.indexOf(item) === -1) {
return { label: "No Results." }
} else {
return {
label: item.Company + " (" + item.Symbol + ")",
value: item.Company
}
}
}));
}
});
},
minLength: that.options.minLength,
select: function (event, ui) {
reRenderGrid();
}
});
I have tried adding an if() statement with the following but that didn't work.
if (data.length === 0) {
// Do logic for empty result.
}
I am able to overwrite the first entry with the text "No Result" if I do the following...
if (data.indexOf(item) === 0) {
return {
label: "No Results."
}
...but if I set data.indexOf(item) === -1 nothing shows up.
I just recently tried the following, and when there is no data, it goes into the loop, however, "No Results" is not being displayed in the menu:
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Company + " (" + item.Symbol + ")",
value: item.Company
}
}));
if (data.length === 0) {
label: "No Results."
}
}
I have also attempted to use the below example from Andrew Whitaker with no luck:
ANDREW WHITACKER'S FIDDLE: http://jsfiddle.net/J5rVP/128/
SOURCE: http://blog.andrewawhitaker.com/2012/10/08/jqueryui-autocomplete-1-9/
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
//$("#message").text("No results found");
}
Fiddle
http://jsfiddle.net/J5rVP/129/
Update
Put the code at the end of your auto-complete setup just after select: function (event, ui) {..}
..........
minLength: that.options.minLength,
select: function (event, ui) {
reRenderGrid();
}, //HERE - make sure to add the comma after your select
response: function(event, ui) {
if (!ui.content.length) {
var noResult = { value:"",label:"No results found" };
ui.content.push(noResult);
}
}
});
Modify the function like this to check for length of data.
success: function (data) {
if(!data.length){
var result = [
{
label: 'No matches found',
value: response.term
}
];
response(result);
}
else{
// normal response
response($.map(data, function (item) {
return {
label: item.CompanyName + " (" + item.SymbolName + ")",
value: item.CompanyName
}
}));
}
}
My answer is almost identical to #neelmeg and #Trever, but I have added an extra check, so user won't be able to select the "no result" message:
$(".my-textbox").autocomplete({
minLength: 2,
open: function () { $('.ui-autocomplete').css('z-index', 50); },
source: function (request, response) {
$.ajax({
url: "/some-url",
type: "POST",
dataType: "json",
data: { prefix: request.term, __RequestVerificationToken: token },
success: function (data) {
if (!data.length) {
var result = [{ label: "no results", value: response.term }];
response(result);
}
else {
response($.map(data, function (item) {
return { label: item.someLabel, value: item.someValue };
}))
}
}
})
},
select: function (event, ui) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
var url = "some-url"
window.location.href = url;
}
}
});
For me the reason, why this messages occured were:
MISSING CSS FILES O JQUERY UI
so adding:
<link rel="stylesheet" href="jqueryui/themes/flick/jquery-ui.css" type="text/css" media="screen" />
<link rel="stylesheet" href="jqueryui/themes/flick/jquery.ui.theme.css" type="text/css" media="screen" />
solved my problem

Categories