I am trying to "filter" a grid based on an option selected from a select drop down.
How do I send the selected option value to the grid when the change event on the select dropdown fires?
My grid datasource is:
dataSourceParts = new kendo.data.DataSource({
serverPaging: false,
serverFiltering: false,
serverSorting: false,
transport: {
read: {
url: ROOT + 'shipment/partsSerialGrid',
dataType: 'json',
type: 'POST',
data: {
enquiryId: enquiryId
}
}
},
pageSize: 25,
error: function(e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
total: "rowcount",
model: {
id: 'id',
fields: {
quantity: {
type: 'number',
editable: false
},
idealForm: {
type: 'string',
editable: false
},
serial: {
type: 'string',
editable: true
}
}
}
}
})
My select event:
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
dataSourceParts.filter({
field: 'test', operator: 'eq', value: 'test' // THIS DOES NOTHING.
});
$('#shippingPartsGrid').data('kendoGrid').dataSource.read();
}
})
I cant confirm this. But since you set filter in dataSourceParts. Shouldn't you be using dataSourceParts.read() instead of $('#shippingPartsGrid').data('kendoGrid').dataSource.read();?
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
$('#shippingPartsGrid').data('kendoGrid').dataSource.filter({
field: 'test', operator: 'eq', value: 'test' // DO IT LIKE THIS
});
}
})
Related
I need to set Kendo grid action button Icon based on value. My code as follows,
function InitProductServicesGrid() {
var prodServiceDataSource = new kendo.data.DataSource({
transport: {
type: "json",
read:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/GetProductServiceDetailsList",
type: "POST",
contentType: 'application/json',
data: GetAdditonalData,
datatype: "json"
},
update:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/SaveProductService",
type: "POST",
contentType: 'application/json',
datatype: "json"
}
},
schema: {
data: function (result) {
return JSON.parse(result.d);
},
model: {
id: "Id",
fields: {
Id: { type: "int" },
ServiceTime: { type: "string" },
IsActive: { type: "boolean"}
}
}
},
requestEnd: function (e) {
if (e.type === "destroy") {
var grid = $("#productServicesGrid").data("kendoGrid");
grid.dataSource.read();
}
},
error: function (e) {
e.preventDefault();
if (e.xhr !== undefined && e.xhr !== null) {
var messageBody = e.xhr.responseJSON.Message;
ShowGritterMessage("Errors", messageBody, false, '../App_Themes/Default/LtsImages/errorMessageIcon_large.png');
var grid = $("#productServicesGrid").data("kendoGrid");
grid.cancelChanges();
}
},
pageSize: 20,
});
$("#productServicesGrid").kendoGrid({
dataSource: prodServiceDataSource,
sortable: true,
filterable: false,
pageable: true,
dataBound: gridDataBound,
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "Id", title: "", hidden: true },
{
field: "ServiceTime",
title: "Time Standard",
sortable: false,
editor: function (container, options) {
var serviceTimeTxtBox = RenderServiceTime();
$(serviceTimeTxtBox).appendTo(container);
},
headerTemplate: '<a class="k-link" href="#" title="Time Standard">Time Standard</a>'
},
{
title: "Action", command: [
{
name: "hideRow",
click: hideRow,
template: comandTemplate
}
],
width: "150px"
}
]
});
}
I wrote a custom template function as follows,
function comandTemplate(model) {
if (model.IsActive == true) {
return '<a title="Hide" class="k-grid-hideRow k-button"><span class="k-icon k-i-lock"></span></a><a title="Hide"></a>';
}
else {
return '<a title="Show" class="k-grid-hideRow k-button"><span class="k-icon k-i-unlock"></span></a><a title="Show"></a>';
}
}
But when I debug the I saw the following value for model value.
I followed this sample code as well. here you can see, I also set the custom template like the sample code. Please help me to solve this. Why I can't access model IsActive value from comandTemplate function.
Updated
When clicking hideRow action, I access the dataItem as follows.
function hideRow(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
if (dataItem.IsActive == true) {
dataItem.IsActive = false;
}
else {
dataItem.IsActive = true;
}
}
Is there any possible way to access data from template function as above or any other way?
I would suggest a different approach because you can't access grid data while rendering and populating grid.
My suggestion is to use two actions and hide it based on the flag (in your case IsActive).
Something like this: Custom command
NOTE: in visible function you can access item!
EDIT: you can access it and change it on dataBound traversing through all data.
Check this example: Data bound
I don't see the advantage of relying on the grid commands. You can render any button you want yourself and and use the dataBound event to bind a click handler:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{
template: function(dataItem) {
const isActive = dataItem.isActive;
return `<a title=${isActive ? "Hide": "Show"} class="k-grid-hideRow k-button"><span class="k-icon k-i-${isActive ? 'lock' : 'unlock'}"></span></a>`
}
}
],
dataBound: function(e) {
e.sender.tbody.find(".k-grid-hideRow").click(evt => {
const row = evt.target.closest("tr")
const dataItem = e.sender.dataItem(row)
dataItem.set("isActive", !dataItem.isActive)
})
},
dataSource: [{ name: "Jane Doe", isActive: false }, { name: "Jane Doe", isActive: true }]
});
Runnable Dojo: https://dojo.telerik.com/#GaloisGirl/eTiyeCiJ
I am using Datatables to display a table and I am pulling a list of datestimes from a MySQL database. These date times are not standard dates and look like this:
12/30/19 # 04:17 pm
How can I sort these accurately with Datatables?
Here is my code:
getRes(function (result) { // APPLIED CALLBACK
$('#resdatatable').DataTable({
data: result, // YOUR RESULT
order: [[ 0, "desc" ]],
autoWidth: false,
responsive: true,
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select id="resstatus'+row.id+'" onchange="changeResStatus('+row.id+')" data-previousvalue="'+row.status+'">', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected');
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected');
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Communicating',
text: 'Communicating'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}, {
id: 'Reallocated',
text: 'Reallocated'
}, {
id: 'No Show',
text: 'No Show'
}];
}
I need to sort bookingdatetime, pickupdatetime, dropdatetime accurately (they are currently being converted into MM/DD/YY in the PHP script)
Maybe you can prepend hidden <span> elements containing the respective unix timestamps in the cells that have dates (by manually parsing the dates). Then using such columns to sort alphabetically would practically sort time-wise.
I load data via an ajax call in dataInit which works and everything works fine BUT none of my columns (only dropdown columns) don't set the id value.
e.g. I have itemId and itemCode properties. I load the data and displays correctly but if I change the value in the drop down then it doesn't bind/update my itemId value.
Essentially I want the dropdown to bind to my id column thus when saving it I get an Id to save.
,{
key: false,
hidden: true,
name: 'itemId',
index: 'itemId',
editable: false
}, {
key: false,
name: 'itemCode',
index: 'itemId',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetItems", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (itemId == array[i].id) {
$(element).append("<option value=" +
array[i].id +
" selected>" +
array[i].code +
"</option>");
} else {
$(element).append("<option value=" +
array[i].id +
">" +
array[i].code +
"</option>");
}
}
}
}
}
});
}
},
editrules: { required: true}
Here is my answer.....Look at the data events. I find the selected row and then I set the cell. The console log was just to test.
{
key: false,
hidden: true,
name: 'userId',
index: 'userId',
editable: false
}, {
key: false,
name: 'userName',
index: 'userName',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetUsers", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (userId == array[i].id) {
$(element).append("<option value=" +
array[i].id +
" selected>" +
array[i].userName +
"</option>");
} else {
$(element).append("<option value=" +
array[i].id +
">" +
array[i].userName +
"</option>");
}
}
}
}
}
});
},
dataEvents: [
{ type: 'change',
fn: function (e) {
var rowId = $("#jqgrid").jqGrid('getGridParam', 'selrow');
$('#jqgrid').jqGrid('setCell', rowId, 'userId', $(e.target).val());
console.log($("#jqgrid").jqGrid('getCell', rowId, 'userId'));
}
}
]
}
whenever i cancelled the updating process from the child node,the child node just merge with root node,i don't find error in the console or i can't find anything suspicious.but after a reload,all becomes normal
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
the updation and deletion works fine by the way,Here is the fiddle
https://jsfiddle.net/me09jLy7/2/
updation:
whenever i create a child to ranikannur gives me 3 children with same name in each root ranikannur,in my database there is only one child is parented by ranikannur but treelist shows it as 3 children in each parent node,the children count 3 is getting from the total ranikannurparent nodes(here tree has 3 ranikannur parent nodes)
i guess.how is this getting the 3 children?
u just try it...
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
I have a Treeview. On selecting the edit of the treenode a kendo grid for Roles will be displayed and few textboxes (where is edit other properties for roles). The kendo grid for roles have checkboxes and Rolenames. My current code is working if I select one checkbox.
What I need is how I get the array of the ids of the roles if I check multiple checkboxes. Tried multiple ways but I am not getting the list of ids when multiple checkboxes are selected. On click edit of the node EditNode is triggered and on click of save the 'click' is trigerred.
Below is my code:
function editNode(itemid) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node }))
.appendTo("body")
.kendoWindow({
title: "Node Details",
modal: true,
open: function () {
console.log('window opened..');
editDS = new kendo.data.DataSource({
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: {// define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { editable: false, nullable: false, type: "string" },
name: { editable: true, nullable: true, type: "string" },
NodeId: { editable: false, nullable: false, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/MenuServices.asmx/getroles",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
datatype: "json",
},
}
});
rolesGrid = $("#kgrid").kendoGrid({
dataSource: editDS,
height: 150,
pageable: false,
sortable: true,
binding: true,
columns: [
{
field: "name",
title: "Rolename",
headerTemplate: '<span class="tbl-hdr">Rolename</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
template: kendo.template("<input type='checkbox' class = 'checkbox' id='chkbx' data-id='#:Id #' />"),
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
}).data('KendoGrid');
},
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var LinKLabel = $('#LL').val();
var roles = $(chkbx).data('roleid');
console.log(PageLocation);
node.text = undefined;
node.set("LINK_LABEL", LinKLabel);
node.set("Roles", roles);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("LINK_LABEL", LinKLabel);
treenode.set("id", Id);
treenode.set("roles", roles);
treenode.LINK_LABEL = LinKLabel;
treenode.ID = Id;
treenode.roles = roles;
var rid = $(chkbx).data('roleid');
$.ajax({
url: "/Services/MenuServices.asmx/UpdateTreeDetails",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ "Json": treenode })
});
console.log(JSON.stringify(treenode));
})
}
I'm assuming you want to get those ids in this line:
var roles = $(chkbx).data('roleid');
Right? What I don't know is the format you want to get that data. With the following code you can get the roles data in an array objects like this { id: 1, value: true }, check it out:
var grid = $("#grid").data("kendoGrid"),
ids = [];
$(grid.tbody).find('input.checkbox').each(function() {
ids.push({
id: $(this).data("id"),
value: $(this).is(":checked")
});
});
Demo. Anyway you want it, you can change it inside the each loop.
Update:
To get only the checked checkboxes, change the selector to this:
$(grid.tbody).find('input.checkbox:checked')
Demo