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
Related
I am trying to populate one of the columns using select box in jqgrid. Below is the code.
$(document).ready(function(){
$("#grid").jqGrid({
url: "./info",
datatype: "json",
mtype: "GET",
ajaxSelectOptions:{
type: "GET",
dataType: "json",
success: function (result) {
console.log(result);
}
},
colNames: ["DeptId", "DeptName", "StuId", "StuName", "StuDoj"],
colModel: [
{ name: "deptId", hidden:true },
{ name:"deptName", width:90, editable:true, edittype:'select', formatter:'select', editoptions:{
dataUrl:'./getDepts',
buildSelect: function(res){
console.log(res);
var s='<select id="dept" name="dept">'
$.each(res,function(idx,obj){
$('#dept')
.append($('<option>', { value : obj.deptId })
.text(obj.deptName));
});
return s+"</select>";
}
}},
{ name: "studentId", hidden:true },
{ name: "studentName", width: 80,editable:true },
{ name: "studentDoj",width: 90,editable:true }
],
pager: "#pager",
rowNum: 5,
rowList: [5, 10, 20],
sortname: "empId",
sortorder: "asc",
sortable:true,
viewrecords: true,
gridview: true,
caption: "MyGrid",
jsonReader: {
repeatitems: false,
id: "empId",
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
});
$("#grid").jqGrid('navGrid','#pager',{add:false,view:true,search:true});
})
In the editOptions for colModel 'deptName' the dataUrl is not called to populate the select box. The jqgrid is populated using /info resturl which fetches the deptName for a particular student. I want the deptName to be of type select box and its value should be same as deptName fetched using info rest url
It should be called, but your data will be newer filled, since you overwrite the success function in ajaxSelectOptions.
In order to get response, please comment the success function or remove it
$("#grid").jqGrid({
url: "./info",
datatype: "json",
mtype: "GET",
ajaxSelectOptions:{
type: "GET",
dataType: "json"
},
....
});
UPDATE: With small changes your code is working fine. Here is a link to your code
Note that the formatter does not have option dataUrl. It is only available in in editing.
I'm trying to use jsGrid in my MVC project as the client would like inline editing and filtering.
However, I cannot get it to load my JSON source into the table.
My js to load the table looks like so:
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "RICInstrumentCode/GetData",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "CREATE",
url: "/api/RICInsrumentCodeTable",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "UPDATE",
url: "/api/RICInsrumentCodeTable/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: $.noop
//deleteItem: function (item) {
// return $.ajax({
// type: "DELETE",
// url: "/api/data/" + item.ID,
// dataType: "json"
// });
//}
},
fields: [
{ name: "Code", type: "text", title: "RIC Instrument Code", width: 150 },
{ name: "Descr", type: "text", title:"RIC Instrument Code Description", width: 200 },
{ name: "RICInstrumentGroupId", type: "select", title: "RIC Instrument Group", items: countries, valueField: "Id", textField: "Name" },
{ name: "Active", type: "checkbox", title: "Is Active", sorting: true },
{ type: "control" }
]
});
});
The loadData is what I've been working on.
and the JSON the is returned from get data looks like so:
[{"Id":1,"Code":"test1","Descr":"first code test","RICInstrumentGroupId":2,"Active":true},{"Id":2,"Code":"APP","Descr":"Apples and bananas","RICInstrumentGroupId":4,"Active":true},{"Id":3,"Code":"1","Descr":"1","RICInstrumentGroupId":1,"Active":true},{"Id":4,"Code":"3","Descr":"3","RICInstrumentGroupId":3,"Active":false}]
So far I have confirmed that the ajax is firing, changed my array titles to match those of the call, and ensured the return is in valid JSON, what else can I do? Why isn't this working?
I was being stupid,
The bit that sets the table height was set to a 100% in a div that had no height, this was causing the table body to render with a height of 0px, changing the height property to auto fixed it because the data was there all along.
Thanks for the advice though!
I don't know if it is required, but when I look on demo examples (OData Service).
The grid loadData function looks bit different than yours.
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "http://services.odata.org/V3/(S(3mnweai3qldmghnzfshavfok))/OData/OData.svc/Products",
dataType: "json"
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
is accept promise rather than ajax function. so that my be the problem
Demo here: http://js-grid.com/demos/
I am trying to get jsGrid working in a project but I am missing something since I can't make it to work correctly. I have read docs carefully several times.
The scenario is as follow:
An AJAX call for get a list of subregion
An AJAX call for get a list of countries (each time I click on pagination a new request should be made in order to get proper values)
From docs under controller section:
loadData is a function returning an array of data or jQuery promise
that will be resolved with an array of data (when pageLoading is true
instead of object the structure { data: [items], itemsCount: [total
items count] } should be returned). Accepts filter parameter including
current filter options and paging parameters when pageLoading is true.
So my PHP function return data in the "proper" format as expected, meaning:
{
data: [items],
itemsCount: [total items count]
}
I have created a Pastebin with the result I get when the AJAX call is made (for the countries result). I believe the data is right now. So, this is how my code looks like:
$(function () {
$.ajax({
type: "GET",
url: "/adminconsolejsgrid/subregion"
}).done(function (subregion) {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
filtering: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
pageLoading: true,
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "/adminconsolejsgrid/countries",
data: filter
});
}
},
fields: [
{name: "country_name", title: "Name", type: "text", width: 100, sorting: true},
{name: "country_abbr", title: "Code", type: "text", width: 5, sorting: true},
{
name: "subregion",
title: "SubRegion",
type: "select",
width: 100,
items: subregion,
valueField: "subregion_id",
textField: "subregion_name"
},
{type: "control"}
]
});
});
});
But still not working for me which mean I am not getting any values on the grid. This pic is an example of what I get:
What I am missing? Any help?
I have Kendo Combobox in that on Change event I am calling a controllers action using Jquery Ajax.For the first time on Select of any item from Combobox the Action is called and I get the required data.
But on ComboxBox focus Out(When i click on any where on the screen) the same action is being called.
My Kendo Combobox is as follows:
$("#Number").kendoComboBox({
dataTextField: "NUM",
dataValueField: "ID",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: ResolveUrl("/CreateMaintainAnalysis/GetAnalysisNumbers/"),
type: "POST",
dataType: "json",
data: function () {
return {
Number: $("#Number").data("kendoComboBox").input.val()
};
}
},
},
requestEnd: function (e) {
if (WebApp.CLAF.LoggedInUser.Info.IS_ANALYST == 'Y') {
e.response.unshift({ ID: -1, NUM: 'Create New Analysis' });
}
else {
e.response.unshift({ ID: -2, NUM: 'Select' });
}
},
serverFiltering: true
}),
filter: "startwith",
suggest: true,
minLength: 5,
highlightFirst: true,
index:0,
change: function (dataItem) {
$.ajax({
type: "POST",
data: { ID: ID },
url: ResolveUrl("/Analysis/Data"),
success: function (result) {
},
});
}
});
This is really very weird behavior and I am not able to catch it up.
Inside dataSource please add autoBind: false, this is by default true, and most often this is the reason for sending an additional API call from inside upon any focus in/out or click events.
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;
},
});