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;
},
});
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/
How can I prevent ajax call to retrieve select2 drop down items on click of select2 user interface element? I want to retrieve select2 drop down items only when I type in search box. Any help would be most appreciated.
$("#ddlItems").select2({
minimumInputLength: 0,
width: '450px',
allowClear: true,
placeholder: "Select",
id: function (data) { return { id: data.Id }; },
ajax: {
quietMillis: 150,
url: getDataUrl,
dataType: 'json',
quietMillis: 100,
global: false,
data: function (term, page) {
return {
clientId: $("#clientID").val(),
pageSize: 20,
pageNum: page,
searchTerm: term
};
},
results: function (data, page) {
return { results: data.items, more: data.isSearchRemaining };
}
}
You have to change your minimumInputLength attribute.
Change it like that :
minimumInputLength: 1,
The ajax request is done when your input length >= minimumInputLength.
So it is logical that when minimumInputLength = 0 , select2 will retrieve the data using the ajax :)
You have an example on here : https://select2.github.io/examples.html#data-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.
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'];
}