Select2 is showing "No result found" message when selecting second time - javascript

I am using Select2 with ajax option and its a multiple selection box. I am able to select the record first time. But after selecting first one if i try to select the next one it is not working.
fiddle link for complete code
$('#select2_ajax_complex_id').select2({
tags: true,
maximumSelectionSize: 10,
minimumResultsForSearch: Infinity,
multiple: true,
minimumInputLength: 1,
placeholder: "Search Employee",
//data:o,
id: function(i) {
return i;
},
initSelection: function(element, callback) {
},
ajax: {
type: 'post',
url: "/echo/json/",
allowClear: true,
dataType: 'json',
delay: 250,
params: {
contentType: "application/json"
},
data: function(term, page) {
//Code for dummy ajax response
return {
json: complex_employee_response,
delay: 0
};
},
results: function(data, page) {
return {
results: data
};
},
cache: false
},
formatResult: function(i) {
return '<div>' + i.name + '(' + i.role + ')' + '</div>';
}, // Formats results in drop down
formatSelection: function(i) {
return '<div>' + i.name + '(' + i.role + ')' + '</div>';
}, //Formats result that is selected
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function(m) {
return m;
} // we do not want to escape markup since we are displaying html in results
})
Can some one have a look and help to resolve this?

Remove below block from your code
//data:o,
id: function(i) {
return i;
},
initSelection: function(element, callback) {
},
By using this code ,your problem will fixed
I have created one demo for the same[Edited in your example]
Just refer this URL
https://jsfiddle.net/7m2nv5yw/

Related

Issues with selectize.js and ajax

In my view i have the following code and i'm trying to get the select box to drop down with the values i send with the callback but unfortunately it does not work.
I was following http://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/ with slight changes her and there to suite my use case.
<script>
$(document).ready(function(){
var root = '{{url("/")}}';
$('#testselect').selectize({
valueField: 'url',
labelField: 'description',
searchField: ['description'],
maxOptions: 10,
options: [],
create: true,
render: {
option: function(data, escape) {
return '<div>' + escape(data.description) + '</div>';
}
},
optgroups: [
{value: 'description', label: 'description'},
],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: root+'/gettimecodes',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data) // Prints my data all well and good.
var object = {description:"description"};
var array = ["Saab", "Volvo", "BMW"];
var json = {
"data":[
{"description":"Saab"},
{"description":"Volvo"},
{"description":"BMW"}
]
}
// callback(array); // Doesn't work. (Array)
// callback(object); // Doesn't work (Object)
// callback(json); // Doesn't work (JSON)
}
});
},
});
});
</script>
If any one could point me in the correct direction it would be greatly appreciated!
Updated with bashers recomendations.
$('#testselect').selectize({
valueField: 'description',
labelField: 'description',
searchField: ['description'],
maxOptions: 10,
options: [],
create: true,
render: {
option: function(data, escape) {
return '<div>' + escape(data.description) + '</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/gettimecodes',
type: 'GET',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res.data)
}
});
},
});
The JSON that is returned in the response
{"data":[{"description":"Crushed blacks "},{"description":"Crushed blacks "},{"description":"Example of crushed blacks"},{"description":"Example of crushed blacks and video noise"},{"description":"Example of heavily de-interlaced artfacts on footage during title sequence - As source"}]}
Your valueField does not exist. url is not a property of the object you pass. Change valueField to description. Then let me know a more specific error if you get one. Also remove optGroups for now. Keep it basic.

Using an external auto complete plugin (jQuery) and i am trying to put my own value in json it was not working

This is the continuation with my previous question posted here I am new to the JSON and ajax trying to put my own value in this link the data as per my requirement.
$("document").ready(function() {
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function(index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
//from here I am customizing the code*/
$("document").ready(function (){
$("#scl_name").mcautocomplete({
// These next two options are what this plugin adds to the autocomplete widget.
showHeader: true,
showHeader: true,
columns: [{
name: 'description',
width: '150px'
}, {
name: 'schoolname',
width: '120px'
}],
// Event handler for when a list item is selected.
/*select: function (event, ui) {
this.value = (ui.item ? ui.item.name : '');
$('#school_Name').text(ui.item ? 'Selected: ' + ui.item.name +this.value);
return false;
},*/
// The rest of the options are for configuring the ajax webservice call.
minLength: 1,
source: function (request, response) {
$.ajax({
url: 'dummy.json',
dataType: 'json',
data: {
featureClass: 'P',
style: 'full',
maxRows: 12,
name_startsWith: request.term,
username: "demo"
},
// The success event handler will display "No match found" if no items are returned.
success: function (data) {
var result;
if (!data || data.length === 0 || !data.schoolname || data.schoolname.length === 0) {
result = [{
label: 'No match found.'
}];
} else {
result = data.schoolname;
console.log(result);
}
response(result);
}
});
}
});
});
with the current one i am getting the output as [object] Now I am not getting any error but i am not getting any value as well :(
This is my html
<input type="text" id="scl_name" class="ipt_Field"/>
Thanks in advance

Select2 does not allow to select value while using select2 ajax

I am trying to use select2 for remote data in angularJS using select2-AJAX, it works fine when i use there given example on http://ivaynberg.github.io/select2/, but when I'm working with my own code, it does not allow me to select value.
$scope.select2Options = {
allowClear: true,
minimumInputLength: 3,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: rootURL.tsURL + "valueSets/dy346:fhir.observation-codes/concepts/_fhir",
dataType: 'json',
quietMillis: 250,
id: function(item) {
console.log(item);
return data.item['CodeableConcept.coding']['Coding.code'];
},
transport: function(params) {
params.beforeSend = function(request) {
request.setRequestHeader("Authorization", userService.tsConfig.headers.Authorization);
};
return $.ajax(params);
},
data: function(term, page) {
return {
criteria: term,
matchType: "StartsWith",
limit: "8",
offset: "0"
};
},
cache: true,
results: 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
var org = normalizeJSONLD.findAllObjectsByType(data['#graph'], "fhir:CodeableConcept");
var object = normalizeJSONLD.normalizeLD(data['#graph'], org);
return {
results: object
};
}
},
formatResult: function(item) {
console.log(item);
return item['CodeableConcept.coding']['Coding.code'] + ": " + item['CodeableConcept.coding']['Coding.display'];
},
formatSelection: function(item) {
return item['CodeableConcept.coding']['Coding.code'];
}
};
In Chrome Dev Tool, the select2 has a class "select2-result-unselectable" which does not allow me to select value.
You are only placing id function inside you ajax call, while it should be placed within the select2Options context as a key...
$scope.select2Options = {
allowClear: true,
minimumInputLength: 3,
ajax: {
url: rootURL.tsURL + "valueSets/dy346:fhir.observation-codes/concepts/_fhir",
dataType: 'json',
quietMillis: 250,
transport: function(params) {
params.beforeSend = function(request) {
request.setRequestHeader("Authorization", userService.tsConfig.headers.Authorization);
};
return $.ajax(params);
},
data: function(term, page) {
return {
criteria: term,
matchType: "StartsWith",
limit: "8",
offset: "0"
};
},
cache: true,
results: 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
var org = normalizeJSONLD.findAllObjectsByType(data['#graph'], "fhir:CodeableConcept");
var object = normalizeJSONLD.normalizeLD(data['#graph'], org);
return {
results: object
};
}
},
formatResult: function(item) {
console.log(item);
return item['CodeableConcept.coding']['Coding.code'] + ": " + item['CodeableConcept.coding']['Coding.display'];
},
formatSelection: function(item) {
return item['CodeableConcept.coding']['Coding.code'];
},
// id should be defined over here...
id: function(item) {
console.log(item);
return data.item['CodeableConcept.coding']['Coding.code'];
}

Select2: how to set data after init?

I need to set an array of data after initializing select2. So I want to make something like this:
var select = $('#select').select2({});
select.data([
{id: 1, text: 'value1'},
{id: 1, text: 'value1'}
]);
But I get the following error:
Option 'data' is not allowed for Select2 when attached to a element.;
My HTML:
<select id="select" class="chzn-select"></select>
What should I use instead of a select element?
I need to set the source of items for search
In onload:
$.each(data, function(index, value) {
$('#selectId').append(
'<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
);
});
Make an <input type="hidden"> element and bind select2 to that. Using .select2 on a regular select box doesn't let you play with the data, it just mostly gives you the UI and post-selection methods.
Source:
Select2 Documentation
Source: https://select2.org/programmatic-control/add-select-clear-items
Add item:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
Clear items:
$('#mySelect2').val(null).trigger('change');
For v4 you'll have to destroy and reconstruct select2 with updated data. Check https://github.com/select2/select2/issues/2830
I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:
$("#group").on('change', function () {
var uri = "/Url/RetrieveNewResults";
$.ajax({
url: uri,
data: {
format: 'json',
Id: $("#group :selected").val()
},
type: "POST",
success: function (data) {
$("#groupchild").html('');
$("#groupchild").select2({
data: data,
theme: 'bootstrap',
placeholder: "Select a Type"
});
},
error: function () {
console.log("Error")
}
});
});
I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.
You can rerender and trigger the select2
render select2
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true
});
after need to change the data data
let dataChange = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
rerender the select2
$('.select2').select2('destroy');
$('.select2').empty();
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true,
data: dataChange
});
trigger select2
$('.select2').trigger('change');
Hope this is the answer for you :3
Here's what I did.
1. Extend select2
Select2.prototype.setAjax = function (ajaxOptions)
{
// Set the new ajax properties
var oAjaxOpts = this.options.get('ajax');
if (oAjaxOpts != undefined && oAjaxOpts != null)
{
for (var sKey in ajaxOptions)
{
oAjaxOpts[sKey] = ajaxOptions[sKey];
}
}
var DataAdapter = this.options.get('dataAdapter');
this.dataAdapter = new DataAdapter(this.$element, this.options);
}
2. Initialize as usual (for example --- yours could be different)
jHtmlFrag.select2({
dropdownParent: $(oData.jDiv),
placeholder: "Select Option",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "",
method: "POST",
dataType: 'json',
delay: 250,
processResults: function (oResults, params)
{
let page = params.page || 1;
// console.log(oResults, (params.page * 10));
return {
results: oResults.data,
pagination: {
more: (page * 10) < oResults.recordsFiltered
}
};
}
}
}).val(null).trigger('change');
3. Set Ajax options dynamically when you feel like by calling the new extension func
jCombo.select2('setAjax', {
url: sUrl,
data: function (params)
{
let query = {
search: params.term,
type: params._type,
page: params.page || 1,
}
return query;
},
});

Unable to select items populated via jsonp in select2

I'm trying to populate a select2 element using geonames data. I have a formatSelection method defined but it will not fire when an item is selected.
Here's the HTML element:
<input id="location" size="30" type="text">​
Select2 binding with format functions:
function locationFormatResult(location) {
var markup = "<table class='location-result'><tr>";
if (location.countryCode !== undefined) {
markup += "<td class='flag-image'><img src='http://www.geonames.org/flags/x/" + location.countryCode.toLowerCase() + ".gif' /></td>";
}
markup += "<td class='location-info'>";
markup += "<div class='location-name'>" + location.name + ", " + location.adminName1 + ", " + location.countryName + "</div>";
markup += "</td></tr></table>";
return markup;
}
function locationFormatSelection(location) {
return location.name + ", " + location.adminName1 + ", " + location.countryName;
}
$(function () {
$('#location').select2({
placeholder: 'Location',
allowClear: true,
width: '260px',
minimumInputLength: 2,
ajax: {
url: 'http://ws.geonames.org/searchJSON',
dataType: 'jsonp',
data: function (term) {
return {
featureClass: 'P',
q: term
};
},
results: function (data) {
return {
results: data.geonames
};
}
},
formatResult: locationFormatResult,
formatSelection: locationFormatSelection,
dropdownCssClass: "bigdrop"
});
});
You can see the full fiddle here: http://jsfiddle.net/6CVbw/1/
Why is selecting an item not working?
I figured it out. When you instantiate the select2 plugin on an element you have to specify an ID attribute. This worked:
$(function () {
$('#location').select2({
id: function(e) { return e.name + '|' + e.adminName1 + '|' + e.countryName },
placeholder: 'Location',
allowClear: true,
width: '260px',
minimumInputLength: 2,
ajax: {
url: 'http://ws.geonames.org/searchJSON',
dataType: 'jsonp',
data: function (term) {
return {
featureClass: 'P',
q: term
};
},
results: function (data) {
return {
results: data.geonames
};
}
},
formatResult: locationFormatResult,
formatSelection: locationFormatSelection,
dropdownCssClass: "bigdrop"
});
});
You can see the updated fiddle here: http://jsfiddle.net/6CVbw/2/

Categories

Resources