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'];
}
Related
How could I disallow a cell in my kendo grid to be 'blank' or 'empty' rather... How could I replace all blank or empties with a 0..
I have a save button grabbing the values from my kendo grid such as below: Everything works fine EXCEPT, it is completely omitting my empty cells.. I want to keep them, just have a 0 value on them...
Save button: want to keep the empties with simply a 0 or N/A..
$('.' + chs).on('click', '#saveChanges', function(e) {
which = $(frm).attr("class");
let dataSource = $("#grid").data("kendoGrid").dataSource,
data = dataSource.data(),
changedModels = [];
if(dataSource.hasChanges) { // only saves cells/row that have been edited/changed, need to keep this
for(var i = 0; i < data.length; i++) {
if(data[i].dirty) { changedModels.push(data[i].toJSON()) }
}
}
let ds = JSON.stringify(changedModels);
$.ajax({
type: "POST",
url: "saveGrid",
dataType: "json",
data: {
id: which,
data: ds
},
success: function(result) {
console.log('yy');
},
error: function(result) {
console.log('nn');
}
});
});
This is my kendo grid initialized:
let dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/popGrid?id=" + which,
dataType: "json"
},
},
batch: true,
schema: {
data: "data",
model: {
id: id,
}
},
});
console.log(id);
$("#grid").kendoGrid({
dataSource: dataSource,
height: 600,
sortable: true,
autoBind: true,
nullable: true,
editable: {
createAt: "top"
},
change: function(e) {
let grid = $("#grid").data("kendoGrid");
let selectedItem = grid.dataItem(grid.select());
let val = selectedItem.id;
console.log(val);
},
selectable: "row",
toolbar: [
{ name: "create" },
{ name: "cancel" }
],
paging: false,
});
I can't understand if you want to POST empty fields as "0" or if you want to SHOW them in the grid as "0", when null or "empty".
But I guess you're talking about posting it as "0". In that case I think you have to do that before posting:
let fieldName = 'myCell';
if (data[i].dirty) {
if (!data[i].hasOwnProperty(fieldName) || // In case field is not present on data
!data[i][fieldName]) { // In case field value is null/undefined/0/false/empty string
data[i][fieldName] = 0;
}
changedModels.push(data[i].toJSON());
}
For multiple field check:
let fieldNames = ['fieldA', 'fieldB', ...],
checkFields = (item) => {
fieldNames.forEach(field => {
if (!item.hasOwnProperty(field) || // In case field is not present on data
!item[field]) { // In case field value is null/undefined/0/false/empty string
item[field] = 0;
}
});
};
Or you can do the same before data is bound to the grid with dataSource.schema.parse.
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/
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.
I have a javascript that has a bunch of parameters and functions inside of it.
ctrl.kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
url: "odata/CodeView",
dataType: "json",
contentType: "application/json"
},
update: {
url: function (data) {
return "api/CodeMapUpdate/" + data.CODE_MAP_ID;
},
dataType: "json",
type: "post",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.read();
if (e.status == 201) {
logger.log("Record Updated: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
destroy: {
url: function (data) {
return "api/CodeMapDelete/" + data.CODE_MAP_ID;
},
dataType: "json",
complete: function () {
ctrl.data("kendoGrid").dataSource.read();
}
},
create: {
url: "api/CodeMapCreate",
dataType: "json",
complete: function (e) {
ctrl.data("kendoGrid").dataSource.sort({
field: "CODE_MAP_ID",
dir: "desc"
});
ctrl.data("kendoGrid").dataSource.filter({});
if (e.status == 201) {
logger.log("Record Created: Record ID = " + e.responseJSON, null, null, true);
} else {
logger.logError(" Save failed " + e.responseJSON.ExceptionMessage, null, null, true);
}
}
},
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data["odata.count"];
},
model: {
id: "CODE_MAP_ID",
fields: {
CODE_MAP_ID: {
editable: false,
type: "number"
},
CODE_NAME: {
type: "string",
validation: {
title: "Required Field",
required: true
}
},
L_NAME: {
type: "string",
validation: {
required: true
}
},
CODE_DATE: {
field: "CODE_DATE",
type: "date",
format: "{0:MM/dd/yyyy}",
validation: {
required: true
}
},
}
}
},
change: function () {
},
//batch: true,
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
sort: {
field: "CODE_MAP_ID",
dir: "desc"
}
//autoSync: true
} })
I am trying to save the entire "dataSource" object as a variable and retrieve it at runtime with ajax.
I am able to do this with eval ("(" + dataSource + ")") but any included functions are no longer executing.
Any idea on a strategy to store/retrieve this type of an object to/from JSON?
here is a simple demo of how to use the 2nd param to JSON.parse to recover stored functions:
var ob={a:1, b:false, c: function(a){ return a * a;} };//a sample object
Function.prototype.toJSON=Function.toString; //extend JSON to cover Functions
var str=JSON.stringify(ob, null, "\t"); //turn sample object into a string:
/* str =={
"a": 1,
"b": false,
"c": "function (a){return a*a;}"
} */
//now turn the string back into an object, using a reviver to re-parse methods:
var ob2=JSON.parse(str, function(a,b){
if(b.match && b.match(/^function[\w\W]+\}$/)){ b=eval("b=0||"+b); }
return b;
});
var n=5; //let's try the method using a number
var n2=ob2.c(5); //apply the method to the number
alert(n2); // shows: 25, the number times itself, verifying that the function works
You might want to be a litle stricter about what you send to eval, maybe use a key schema in addition to matching properties that simply look like functions. you can beef-up the regexp to be a little stricter, but for this quick demo of the JSON.parse() parameter, it all works just fine.
In this case, since you are collecting the properties of the JSON, there's no chance of running into the security issues that eval() use can facilitate. Those problems stem from sending one user's input to another user without filtering, not when you jump-start code the client itself produced last time...
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;
},
});