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

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));

Related

Kendo grid button click arguments

I have a kendo grid with a button column. When the button is clicked, I want it to call a javascript function with the row's data as parameters. Here's what I have so far
$(grd).kendoGrid({
dataSource: ds,
detailInit: detailInit,
columns: [ {field: "foo", title: "bar" },
{field: "Y" },
{command: { text: "MyButton", click: doStuff } } ]
});
function doStuff(e)
{
//e is click events but I want to pass in data from the row instead
//following is code I found here but item is null for me
var row = $(this).closest("tr");
var item = $(grd).data("kendoGrid").dataItem(row);
}
This will give you the data pertaining to the row which the button was clicked.
function doStuff(e) {
var tr = $(e.target).closest("tr"); // get the current table row (tr)
var item = this.dataItem(tr); // get the date of this row
alert(item.PropertyName);
}

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.

Display hyperlink value in kendo ui grid column

I have created columns dynamically in the kendo ui grid. The data displayed in the columns could be date , string integer, hyperlinks or any other type.
Data in the column can be integer/hyperlink at the same time. Means for a particular record the data in column can be integer. For next record same column can have a hyperlink value.
I have created fields and added that in the grid.
How can I do this.
You can always set a function against the template of the column you wish to format and conditionally return the content of what you want to appear.
This could look something like this:
var dataSource = new kendo.data.DataSource({
data: [
{ Id:1, val: "value" },
{ Id:"http://google.com", val: "another value" }
]
});
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "Id",
template: function (dataItem) {
if (typeof dataItem.Id == "string") {
return "" + dataItem.Id + "";
} else {
return dataItem.Id;
}
}
}],
dataSource: dataSource
});
});

Get value of hidden column

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;
...
}

jqgrid: Change editable cell to not editable according to the cell value in form editing

My problem is that i want to change the cell being editable or not in the edit form according to the content of the cell of the row that is selected to be edited.
I used Oleg's example to this link: JQGrid: Dynamically set a cell to uneditable based on content to figure out how to change the cell from editable to not editable but i cannot get the cell value in order to compare it and decide if i want to change the edit option of the cell.
UPDATED CODE:
var Setcelluneditable=function(form) {
return function (form) {
var id = jQuery(list).getGridParam('selrow');
var ret = jQuery(list).jqGrid('getRowData',id);
alert("Arrived="+ret.Arrived);
if (ret.Arrived=='Yes')
{alert("hello"+id);
jQuery(list).setCell(id,'Arrived','',{color:'red'}, editable:'0'});}
}
};
jQuery(list).jqGrid('navGrid',pager,{edit:true,add:true,del:true,search:false,view:true, reload:true},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterEdit: true,
recreateForm: true,
ajaxEditOptions: {cache: false},
beforeInitData : Setcelluneditable("#editmod")
},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterAdd: true,
recreateForm: true,
drag: false
},
{},
{},
{},
{});
This does not seem to work because i change the Grid that has already been constructed.
I think i found out the way to do that but it does not seem to me the best one can have:
onSelectRow: function(id){
var ret = jQuery(list).jqGrid('getRowData',id);
if (ret.Arrived=='Yes')
{
jQuery(list).setColProp('Arrived',{editable:false});}
else { jQuery(list).setColProp('Arrived',{editable:true});}}
I change the ColProp every time one Selects a Row.
selRowId = $(list).jqGrid ('getGridParam', 'selrow');
var cm = $(list).jqGrid('getGridParam', 'colModel');
for(x=0; x<cm.length; x++){
if(cm[x].name == 'ID'){
$('#' + selRowId + '_' + cm[x].name).attr('disabled', true);
}
}
code in onSelectRow event

Resources