Get value of hidden column - kendo-ui

I have added columns dynamically in kendo ui grid. I have added a hidden column in the grid as below.
($(document.getElementById(divId))).kendoGrid({
columns: columns,
dataSource: masterData,
pageable: {
pageSize: 10
},
groupable: true,
sortable: true,
filterable: true,
scrollable: true,
change: onChange,
selectable: "multiple",
dataBound: RowDataBound,
schema: {
model: {
id: "MasterColID"
}
}
}).data("kendoGrid");
On the click of the row , I am trying to get the value of the MasterColID in the onchange event as below
var dataItem = this.dataSource.view()[this.select().closest("tr").index()];
var masterID = dataItem["ID"]; //or dataItem.MasterColID;
But everytime I check the varaible masterID i undefined.
Please anyone can help me on this.
Thanks

Try this:
var gridData = $('.k-grid').data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
alert(selectedRowData.MasterColID);

Telerik Grid column:
columns.Bound(model => model.Id).ClientTemplate("#= cba.GridActions(data) #").Title("").Width(100).Sortable(false);
JS function:
function GridActions(data) {
var MasterColID = data.MasterColID;
...
}

Related

Which event gets fired when delete row occurs?

Grid contains after save row event "jqGridInlineAfterSaveRow" which works if you edit or add row.
//--Bind events...
console.log('Bind events...');
$("#jqGrid").bind("jqGridInlineAfterSaveRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridInlineAfterSaveRow');
var item = $(this).jqGrid('getLocalRow', rowid);
console.log(item);
console.log('BEFORE:');
saveObject(item);
console.log('AFTER:');
});
What is name of the event for delete row? i need to bind my JS function for delete row.
UPDATE 1
I am trying following option now, but no luck...
}).jqGrid("navGrid", "#jqGridPager", {edit: false, add: false, del: false, refresh: false, view: false,search: false,
delfunc: function (rowids) {
console.log(rowids);
}
})
UPDATE 2
I think issue is with delete buttons at row level not at footer
see the screenshot [enter image description here][1]
data:rdata,
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: { delfunc : function (id){
console.log(">>>>>>>>>>>>>>>>1");
}}
}
},
UPDATE 3
Based on Oleg's input, i have changed the code as following:
$("#jqGrid").bind("jqGridAfterDelRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridAfterDelRow');
console.log(rowid);
var item = $(this).jqGrid('delRowData ', rowid);
console.log(item);
console.log('BEFORE:');
console.log('AFTER:');
});
But now, i am not getting deleted row object??? Actually, i need to get the some of the fields from deleted row e.g. ID. and above binding function will in turn call server side ajax function.
UPDATE 4
Thanks to Oleg for supporting beyond... Here is the code i have mashup from one of the answers from him.
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editbutton : true,
delbutton : true,
editOptions: {},
addOptions: {},
delOptions: {
onclickSubmit: function(options, rowid) {
console.log("delOptions::onclickSubmit");
var grid_id = $.jgrid.jqID(grid[0].id);
var grid_p = grid[0].p;
var newPage = grid[0].p.page;
var rowdata = grid.getLocalRow(rowid);
// DELETE GRID LOCAL ROW
grid.delRowData(rowid);
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
}
}
},
You can use "jqGridAddEditAfterComplete" event, which will be triggered after deleting of rows by delGridRow, or you can use "jqGridAfterDelRow" alternatively, because delGridRow calls delRowData internally and jqGridAfterDelRow will be triggered by delRowData.
For deleting row use below code snippet:
$('#gridId').jqGrid('delRowData',rowid);
$("#yourGridTable").jqGrid(
"navGrid",
"#yourGridTablePager",
{
del: true
},
{},
{},
{
// This event is fired when delete button is pressed in pager
//
beforeSubmit:function(){
console.log("After delete button of pager is clicked");
}
}
);

jqGrid getGridParam('colModel') missing information

I would like capture the colModel for my jqGrid when the page unloads and store it in session so the next time the user comes to the page it can be loaded automatically. But, the information returned by ('#contract_grid').getGridParam('colModel') is missing part or all of the information in searchoptions for the grid columns.
Any idea why this is or how to capture the full colModel? The grid works great on the initial load but without the other searchoptions params, the filter bar features/menus don't work when I refresh the page from the colModel stored in session.
Create the default colModel for the grid
var defaultColModel =
[
{name:'REQUESTID'
,index:'requestID'
,label:'Request ID'
,search:true
,stype:'text'
,width:75
,key:true
,hidden:false
},
{name:'REQUESTEDDATE'
,index:'requestedDate'
,label:'Request Date'
,sorttype:"date"
,search:true
,width:50
,searchoptions:{
dataInit:function(el){jQuery(el).daterangepicker(
{
arrows:false
, dateFormat:'yy-mm-dd'
, onClose: function(dateText, inst){ jQuery("#contract_grid")[0].triggerToolbar();}
, onOpen: function() {
jQuery('div.ui-daterangepickercontain').css({"top": jQuery('#mouseY').val() + 'px', "left": jQuery('#mouseX').val() + 'px' });
}
});
}
}
,hidden:false
},
{name:'BUSINESSOWNERPERSONID'
,index:'businessOwnerPersonID'
,label:'Business Owner'
,search:true
,stype:'select'
,width:100
,hidden:false
,searchoptions: {
dataUrl: 'cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID',
buildSelect: function(resp) {
var sel= '<select><option value=""></option><option value="7583,1636">My Reports</option>';
var obj = $.parseJSON(resp);
$.each(obj, function() {
sel += '<option value="'+this['lk_value']+ '">'+this['lk_option'] + "</option>"; // label and value are returned from Java layer
});
sel += '</select>';
return sel;
},
dataEvents: [{
type: 'change',
fn: function(e) {
alert(this.value)
}
}]
}
}
];
When user navigates away from page, save the grid to session so it loads when they come back
$(window).on('beforeunload', function(){
takeSnapshot();
});
function takeSnapshot(){
var gridInfo = new Object();
gridInfo.colModel = jQuery('#contract_grid').getGridParam('colModel');
gridInfo.postData = jQuery('#contract_grid').jqGrid('getGridParam', 'postData');
var snapshotData = JSON.stringify(gridInfo);
$.ajax({
url: "actions/act_filter.cfc?method=takeSnapshot",
type: "POST",
async: false,
data: {gridName:'contract_grid'
,gridParamName:'contractGridParams'
,filterData:snapshotData
}
});
}
Create grid variable
var myGrid = jQuery("#contract_grid").jqGrid({
url: 'cfc/com_ajxRequestNew.cfc?method=getReqJSON&returnformat=json',
datatype: 'json',
postData: {filters: myFilters},
mtype: 'POST',
search: true,
colModel: defaultColModel,
altRows: true,
emptyrecords: 'NO CONTRACTS FOUND',
height: 400,
width: 1200,
sortname: lastSortName,
sortorder: lastSortOrder,
page: lastPage,
pager: jQuery('#report_pager'),
rowNum: lastRowNum,
rowList: [10,20,50,100],
viewrecords: true,
clearSearch: false,
caption: "Contracts Dashboard",
sortable: true,
shrinkToFit: false,
ajaxSelectOptions: {type: "GET"},
gridComplete: function() {
//set the selected toolbar filter values
var myFields = JSON.parse(myFilters);
//set fields in form at top. filter contains index value so get corresponding name value because its used in the column label #gs
if ( myFields['rules'].length > 0 ) {
for (var i=0; i < myFields['rules'].length; i++ ) {
$.each(defaultColModel, function(j) {
if(this.index == myFields['rules'][i]['field'] ) {
thisFieldName = this.name;
jQuery('#gs_' + thisFieldName).val( myFields['rules'][i]['data'] );
}
})
}
}
}
});
jQuery("#contract_grid").navGrid('#report_pager',{
edit:false,
add:false,
del:false,
search:false,
refresh:false
}).navButtonAdd("#report_pager",{ caption:"Clear",title:"Clear Filters", buttonicon :'ui-icon-trash',
onClickButton: function() {
jQuery.ajax({
url: "/assets/js/ajx_clearFilter.cfm?showHeader=0",
async: false,
type: "POST",
data: ({variableName:'session.contractGridParams'})
});
myGrid[0].clearToolbar();
}
}).navButtonAdd("#report_pager",{ caption:"Restore",title:"Restore Default Grid Columns and Filters", buttonicon :'ui-icon-refresh',
onClickButton: function() {
window.location = '?page=dsp_requestListingNew&clearSession=1';
}
}).navButtonAdd("#report_pager",{
caption: "Export",
title: "Export to Excel",
buttonicon :'ui-icon-document',
onClickButton: function(e){
jQuery("#contract_grid").jqGrid('excelExport',{url:'includes/act_requestListingExport.cfm'});
}
}).navButtonAdd("#report_pager",{
caption: "Columns",
buttonicon: "ui-icon-calculator",
title: "Select and Reorder Columns",
jqModal: true,
onClickButton: function(e){
$('#contract_grid').jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
}
}).navButtonAdd("#report_pager",{
caption: "Save",
title: "Save Snapshot",
buttonicon :'ui-icon-disk',
onClickButton: function(e){
takeSnapshot(0);
$('#fltrFrmLink').click();
}
});
jQuery("#contract_grid").jqGrid('filterToolbar', {
stringResult : true
, searchOnEnter : true
, autoSearch : true
, beforeClear : function() {
//set sortnames
var sn = jQuery("#contract_grid").jqGrid('getGridParam','sortname');
//set sort orders
var so = jQuery("#contract_grid").jqGrid('getGridParam','sortorder');
so = "desc";
//set grid params
jQuery("#contract_grid").jqGrid('setGridParam',{ sortorder:so, sortname:sn });
}
});
colModel returned by ('#contract_grid').getGridParam('colModel') on unload. searchoptions is missing everything for REQUESTEDDATE. Part of dataEvents and all of buildSelect are missing for BUSINESSOWNERPERSONID.
[{"name":"REQUESTID",
"index":"requestID",
"label":"Request ID",
"search":true,
"stype":"text",
"width":75,
"key":true,
"hidden":false,
"title":true,"lso":"",
"widthOrg":75,"resizable":true,"sortable":true},
{"name":"REQUESTEDDATE",
"index":"requestedDate",
"label":"Request Date",
"sorttype":"date",
"search":true,
"width":50,
"searchoptions:{},
"hidden":false,
"title":true,
"lso":"",
"widthOrg":50,
"resizable":true,
"sortable":true,"stype":"text"},
{"name":"BUSINESSOWNERPERSONID",
"index":"businessOwnerPersonID",
"label":"Business Owner",
"search":true,
"stype":"select",
"width":100,"hidden":false,
"searchoptions":{"dataUrl":"cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID",
"dataEvents":[{"type":"change"}]},
"title":true,
"lso":"",
"widthOrg":100,
"resizable":true,
"sortable":true}]
JSON don't support serialization of functions. So the functions from searchoptions.dataInit, searchoptions.buildSelect and all other which you use in colModel will be discarded after you use JSON.stringify.
It's important to know which version of jqGrid/free jqGrid or Guriddo jqGrid JS you use. Starting with jqGrid 4.7 one can define template in colModel with string value (see the pull request). In the way you will have the main information in colModel which can be serialized using JSON.stringify.

How to set schema and column property in Kendu Grid dynamically

I am using kendu grid with report data,grid is working perfectly in normal case but my problem is that column and schema property of grid will not be static, that's why i want to add it dynamically,but I am unable to set it.
Here is my code:
$(document).ready(function () {
var obj = {
fields: {
}
};
var Column1;
$("#grid").kendoGrid({
dataSource: {
type: "data",
transport: {
read: function (options) {
$.ajax({
type: "GET",
url: "http://localhost:3833/Service1.svc/GetJSON1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var t2 = msg.GetJSON1Result;
var data1 = $.parseJSON(t2.data);
Column1 = t2.columns;
var t11 = Column1;
obj = {
fields: {
}
};
$.each(Column1, function (i, value) {
obj.fields[value.field] = { type: "number" };
}
);
var Schema1 = {
model: obj
}
var gridDetails = $("#grid");
**//Setting schema to grid but it's not effective**
gridDetails.schema = Schema1;
**//Setting schema to grid but it's not effective**
gridDetails.columns = Column1;
options.success(data1);
options.success(Schema1);
options.success(Column1);
}
});
}
},
pageSize: 50,
serverFiltering: false ,
serverSorting: false,
serverPaging: false,
},
height: 550,
reorderable: true,
filterable: true,
sortable: true,
pageable: true,
scrollable: true,
resizable: true,
groupable: true
});
});
please help me. I am new to kendu
Regards,
Ajeet Kumar
To change the grid columns you need to destroy it first and then initialize it again. Here is some code:
var grid = $("#grid").data("kendoGrid");
var options = grid.options;
grid.destroy();
options.columns = [ /* set the columns */ ];
grid.destroy();
$("#grid").empty().kendoGrid(options);

Dynamic resize of kendo grid column not proper in IE10

I am trying to resize the kendo grid column using a popup. It works well in all browsers except IE10. The header columns won't resize along with content columns in the grid.
I have created a sample. The difference can be seen when we run it on IE 10 and chrome
http://jsfiddle.net/pavancbz1/6LFYM/4/
The sample has a grid with 3 columns. The column indexes can be 0,1,2 in the pop up to resize the respective column.
$(document).ready(function() {
var window = $("#window"),
undo = $("#undo")
.bind("click", function() {
window.data("kendoWindow").open();
undo.hide();
});
var onClose = function() {
undo.show();
}
if (!window.data("kendoWindow")) {
window.kendoWindow({
width: "280",
title: "Pop up",
actions: [
"Minimize",
"Maximize",
"Close"
],
close: onClose
});
}
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "http://demos.kendoui.com/service/Products",
dataType: "jsonp"
}
},
pageSize: 5,
},
selectable: "multiple row",
pageable: {
buttonCount: 5
},
scrollable: true,
groupable: false,
resizable: true,
columns: [
{
field: "ProductName",
width: 'auto',
title: "Product Name"
},
{
field: "UnitPrice",
width: 'auto',
title: "Unit Price",
format: "{0:c}"
},
{
field: "UnitsInStock",
width: 'auto',
title: "Units In Stock"
}
]
});
var IncreaseWidth = function (e) {
if (e.type != "keypress" || kendo.keys.ENTER == e.keyCode) {
var grid = $("#grid"),
Index = $("#index").val(),
tablewidth = grid.find('table').width();
grid.find('table').width(tablewidth+20);
columnwidth = grid.find('colgroup:first').find('col:eq(' + Index + ')').width();
grid.find('colgroup').find('col:eq(' + Index + ')').width(columnwidth+20);
}
},
DecreaseWidth = function (e) {
if (e.type != "keypress" || kendo.keys.ENTER == e.keyCode) {
var grid = $("#grid"),
Index = $("#index").val(),
tablewidth = grid.find('table').width();
grid.find('table').width(tablewidth-20);
columnwidth = grid.find('colgroup:first').find('col:eq(' + Index + ')').width();
grid.find('colgroup').find('col:eq(' + Index + ')').width(columnwidth-20);
}
};
$(".Increase").click(IncreaseWidth);
$(".Decrease").click(DecreaseWidth);
});
Any solutions to this problem ?
For anyone having similar issue, here's quick work around I used to deal with column resize problem.
Key observation on this problem is that grid column will realign properly once user adjusts the column manually.
So, in my workaround, I basically hide and show first column and force grid columns to re-size and automatically realign columns properly. Column must re-size after grid receive all its data though. I used amplify for custom messaging, but that implementation detail is not crucial as long as code can automatically force column re-size on grid after data is received.
For example,
var dataSource = new kendo.data.DataSource({
type: 'json',
transport: {
read: config.AppBasePath + '/Home/GetSomething',
parameterMap: function (data, type) {
if (type == 'read') {
return {
id: messageId
};
}
}
},
pageSize: 10,
requestEnd: function (e) {
amplify.publish(config.Messages.ShowWindowComplete);
}
}),
....
amplify.subscribe(config.Messages.ShowWindowComplete, function () {
messageHistoryKendoGridElem.data('kendoGrid').hideColumn(1);
messageHistoryKendoGridElem.data('kendoGrid').showColumn(1);
});
Hope this help anyone who is facing similar issue.

How to get row index and cell index of row click kendo grid

I have added onchange event for kendo-ui grid.
In that I am trying to get the ID value for that particular row. I have added an image column as first column in the grid. What I want is when the image is clicked, I want to open a image url.
So, basically what I want is that when I click the row, I want to get the clicked row index and also I want to get the clicked cell Index in that row.
So based on the row clicked and if it is not the first cell clicked, I want to display alert. If I the first cell is clicked I want to open image.
How can I get this index.
I have set selectable : row in the kendo-ui grid
Please help me on this.
Please try with below code snippet.
function onDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
$(grid.tbody).on("click", "td", function (e) {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
alert(rowIdx + '-' + colIdx);
});
}
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
dataType: "jsonp"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: onDataBound,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
width: 150
}
]
});
});
<div id="Grid"></div>
If all you need is knowing the row and column index in the table you can do:
$(grid.tbody).on("click", "td", function(e) {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
console.log("row:", rowIdx, "cell:", colIdx);
});
Where I set a click handler for clicking in the cells of the grid.
Then I find to which row (<tr>) that cell belongs to using jQuery closest.
Next use jQuery index for finding the index of that row in the table.
Do the same for finding the cell index inside the row.
But maybe there are simpler ways as detecting if the user clicked on an image, or set some CSS class in the image and then check if the clicked cell has that class,...
EDIT If in addition you want to retrieve the original item inside the click handler. Add
var item = grid.dataItem(row);
From there, you can get id or any other field for validation.
Example here : http://jsfiddle.net/OnaBai/MuDX7/
Kendo has introduced frozen columns since the question has been answered so I think it deserved a little update to deal with that feature.
When you have a frozen column, the grid will create new header / content tables to manage the frozen columns. If you freeze a column, it will move item linked to this column from the regular grid's tbody / thead to the lockedContent / lockedHeader (the opposite is also true).
If you get the index using the accepted answer, you'll get the index of the cell within the tbody (or -1 if the cell is frozen). The real question is what do you want to do with the column index? If you really want an index number, you may have to adjust the value by adding the number of columns in the lockedContent depending on your needs. However, if your final goal is to get the grid's column object, this can be done by using the th element:
var row = cell.closest("tr");
var body;
var header;
if (cell.closest(grid.lockedContent).length) {
body = grid.lockedContent;
header = grid.lockedContent;
} else {
body = grid.tbody;
header = grid.thead;
}
var rowIndex = $("tr", body).index(row);
var columnIndex = $("td", row).index(cell);
var columnField = header.find("th").eq(columnIndex).attr("data-field");
var column;
$.each(grid.columns, function () {
if (this.field === columnField) {
column = this;
return false;
}
});
Disclaimer: just to add a level of complexity, you should also consider that kendo has also introduced a multiple column header feature that may invalidate my code above.
For the cell index, kendo grid has a method cellIndex(cell)
var cell = $("#grid td:eq(1)");
console.log(grid.cellIndex(cell));

Resources