Kendo Grid keydown event - javascript

I have initiated a Kendo Grid using Kendo directives. How do I catch the keydown/keypress event of the grid? My final objective is to populate a grid column based on user input of another column. For example, populate the phone number when the first name is entered. For that I believe I have to use the Kendo Grid edit and the keypress events and do a search on the user input, unless there's a better way to do it. Is this possible?
This is how I initialized the grid:
<section id="dashboard-view" class="mainbar" data-ng-controller="dashboard as vm">
....
<div kendo-grid="vm.testGrid" k-options="vm.testGridOptions" k-rebind="vm.testGridDataSource.data" k-on-edit="vm.onEdit(kendoEvent)"></div>
....
</section>
Options defined in my JavaScript file:
vm.testGridOptions = {
columns: [
{ field: "Id", title: "ID" },
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "Phone", title: "Phone" },
{ command: ["destroy"] }
],
toolbar: ["create", "save", "cancel"],
dataSource: vm.testGridDataSource,
editable: {
createAt: "bottom"
},
height: 400,
autoBind: false
};
vm.onEdit = function (e) {
//if grid column == Id && keypressed == Tab key
//search
};
The grid is on batch edit mode.

You can find current column/field name based on the index. Then filter the dropdown present in column next to it: (this is just a sample code, please replace DOM ids with your code)
vm.onEdit = function (e) {
var header = vm.thead;//grid header
var index = vm.cellIndex(e.container);//current cell index
var th = $(header).find("th").eq(index);
var colName = $(th).data("field");//fieldname for current cell
var dataItem = e.model;//row model
if(colName=='LastName')
{
var phoneDropDown = e.container.find("#PhoneDropDownId").data("kendoDropDownList");
if (phoneDropDown) {
phoneDropDown.dataSource.filter({ field: "Phone", operator: "eq", value: e.model.LastName });
}
}
};

Since the Kendo Grid doesn't have a native event for this I used the JQuery onBlur event.
vm.onEdit = function (e) {
alert("Edit event fired");
$('input.k-input.k-textbox').blur(function (f) {
alert("Blur event fired");
}
};

Related

How to disable Kendo Datapicker and Dropdown which is inside a Kendo grid (Jquery)

Background
I have a Kendo Grid with checkboxes, dropdownlist and datepicker. I am using row template functionality to add these controls on the grid. Below is the code for my grid.
This is how I build my Kendo Grid
$("#firstReqGrid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["save"],
columns: [
{ field: "claimId", title: "ClaimID", width: 40 },
{ field: "lineCnt", title: "Lines", width: 10 },
{ title: "Med Requested", field: "medRecRequested", template: '<input type="checkbox" #= medRecRequested ? \'checked="checked"\' : "" # class="chkbx" />', width: 25, editable: function (e) { return false; } },
{ title: "EOB", field: "eobChk", template: '<input type="checkbox" #= eobChk ? \'checked="checked"\' : "" # class="chkbx" />', width: 25, editable: function (e) { return false; } },
{ title: "Claim", field: "clmChk", template: '<input type="checkbox" #= clmChk ? \'checked="checked"\' : "" # class="chkbx" />', width: 25, editable: function (e) { return false; } },
{ field: "MedRecRcvd", title: "Med Rec Rcvd", width: "30px", editor: medRecRcvdDropDownEditor, template: "#=MedRecRcvd.MedRecRcvdName#" },
{
field: "dateReceived", title:"Date Rcvd", format: "{0:dd MMM yyyy}", width: 30, editor: function (container, options) {
var input = $("<input/>");
input.attr("name", options.field);
input.appendTo(container);
input.kendoDatePicker({});
}
},
{ title: "Memo", width: 40, template: '<input type="k-button" onclick="return addMemo(#=claimId#)" class="k-button" name="btnMemo" value="Memo" />' }],
editable: true,
dataBound: function (e) {
/* This code disables all the checkboxes in the grid*/
$("#firstReqGrid :input").attr("disabled", true);
// var grid = $("#firstReqGrid").data("kendoGrid");
// var pageSizeDropDownList = grid.wrapper.children.find(".k-dropdown select").data("kendoDropDownList");
//var dropDown = e.container.find("[data-role='dropdownlist']").data("kendoDropDownList");
//if (dropDown) {
// dropDown.readonly();
//}
}
});
What I am trying to achieve
I want to be able to disable Datepicker and Dropdownlist if certain conditions are met. I was planning on checking for those "conditions" in the databound event of the grid and if conditions were met then disable datepicker and dropdownlist. I am aware of the datepicker.enable(false) event but in order to do that I need an id which I don't have in this instance. Same goes for dropdownlist list as well; I need an ID to disable the attribute. I need help on how to go about adding an ID for datepicker and dropdownlist with the code I have layed out. So that I can refer to that ID in grid databound event and turn on the disable property. Or if there is any other way I am open for suggestions. Thanks a lot.
You can handle the edit event (documentation) to do the following:
Do you custom business logic to determine if the input should be enabled/disabled
If disabling, then get the input
Then get the input's name
Do a conditional check to see if you want to get the kendoDatePicker or the kendoDropDownList
Call the enabled method with the result of the business logic.
Here is an example:
edit: function(e) {
if (SomeBusinessLogicHere()) {
var input = e.container.find('input');
var name = input.attr('name');
if (name === 'my date field') {
var datepicker = input.data('kendoDatePicker');
datepicker.enable(false);
}
}
}
Fiddle: https://dojo.telerik.com/uJidaKIf
FYI - If you wanted to prevent the editor from showing up in the first place you could handle the beforeEdit event (documentation) and simply call e.preventDefault() if your business logic is true.

Checkbox select all row with same field? Using kendo-ui

$(function () {
var grid = $("#grid").kendoGrid({
dataSource: { data: items, pageSize: 20 },
sortable: true,
pageable: true,
columns: [
{
title: "Select All",
template: '<input type="checkbox" class="chkbx" />',
{ field: "Test1", title: "A" },
{ field: "Test2", title: "B" },
{ field: "Test3", title: "C" },
}).data("kendoGrid");
For exemple when I select checkbox at Test1 I want to select all line who have same data in field test 3.
You can have a function on checkbox click:
$(document).on("click", ".chkbx", function() {
});
Check if the class is the same.
Then you can do your logic inside the function
if ($(this).is(':checked')) {
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
console.log(selectedItem); // selected row object;
// loop elements, compare your values and and select lines/checkboxes
} else {
}
How to select a particular row problematically
var row = grid.element.find("... whatever your criteria will be");
grid.select(row);

CellValueChanged event in master detail of ag-grid

I am developing an ag-grid with master-detail set to true, the first row of master-detail has a editable cell i.e. "contractID", I want to populate other cells of the master-detail depending upon the fetched contractID.
I tried adding cellValueChanged in the columnDef and also tried to set params.api.rowModel.gridApi.cellValueChanged explicitly in onFirstDataRendered method for the detailGrid, but found no luck.
Master detail grid code:
detailCellRendererParams = {
detailGridOptions: {
columnDefs: [
{ headerName: "Contact ID", field: "contractId", editable: true, [cellValueChanged]: "cellValueChanged()" },
{ headerName: "Contact Name", field: "contractName" },
{ headerName: "Category", field: "category" }]
}
}
onFirstDataRendered(params) {
params.api.rowModel.gridApi.cellValueChanged = function (params) {
console.log("cellChanged");
}
}
In case someone still wonders, in detailGridOptions add:
onCellValueChanged: function ($event) {
// your code here
},
This will be triggered every time you change cell value.
Fixed the problem using custom cellRenderer and added an eventListener for change event. I just wanted to have this functionality on the first row of the grid, so added a condition to the rowIndex.
detailCellRendererParams = {
detailGridOptions: {
columnDefs: [{headerName: "Contact ID",field: "contractId",editable: true,
cellRenderer: (params) => {
params.eGridCell.addEventListener('change', (e) => {
this.getDetails(e.target.value);
})
},
{headerName: "Contact Name", field: "contractName"},
{headerName: "Category",field: "category"}]
}
}
getDetails(id): void {
this.apiService.getDetails(id)
.subscribe(result => {
this.gridApi.detailGridInfoMap.detail_0.api.forEachNode(node=> {
if(node.rowIndex == 0){
node.data = result;
node.gridApi.refreshCells();
}}
);
})}

DGrid Editor - Changing the Displayed Value when Trying to Edit a Text Cell

I'm using a DGrid editor column to edit the contents of a store. Of the fields that I want to be able to edit, one is an object. When I click on the field to edit it, what I want is for the value displayed in the editor to match the value displayed by the grid when not editing. The cell formatting just shows the value of the object, but when I click on the field to edit it, instead of the object's value, I instead the field is populated with '[object Object]'. I can still edit it (though the results of doing so is that the field will display 'undefined' until I refresh the page, but I could just force a refresh after the change), but can't seem to get it to show what I want.
Here's the set up code:
// build the store
this.postStore = Observable(Memory({
data: posts
}));
var formatCategory = function(object, data, cell) {
cell.innerHTML = object.category.value;
};
var formatAuthor = function(object, data, cell) {
cell.innerHTML = object.author.value;
};
var formatDate = function(object, data, cell) {
cell.innerHTML = new Date(object.dateCreated).toISOString();
};
// the columns displayed in the grid
var columns = [
selector({
field: 'checkbox',
label: ' ',
selectorType: 'radio',
width:33
}),
{
label: "Author",
field: "author",
width: 120,
renderCell: formatAuthor
},
editor({
label: "Title",
field: "title",
editor: "text",
editOn: "click",
width: 200
}),
editor({
label: "Text",
field: "text",
editor: "text",
editOn: "click",
width:500
}, Textarea),
editor({
label: "Category",
field: "category",
editor: "text",
editOn: "click",
width: 150,
renderCell: formatCategory
}),
{
label: "Date",
field: "date",
renderCell: formatDate,
width: 120
}
];
if (this.postGrid) {
this.postGrid.set("store", this.postStore);
} else {
var SelectionGrid = new declare([OnDemandGrid, Selection, Keyboard, editor, selector, DijitRegistry, ColumnResizer]);
this.postGrid = new SelectionGrid({
store: this.postStore,
columns: columns,
selectionMode: 'none',
sort: [{attribute: "date", descending: false}]
}, this.postGridDiv);
this.postGrid.startup();
this.postGrid.on("dgrid-select, dgrid-deselect", lang.hitch(this, this._postSelected));
this.postGrid.on("dgrid-datachange", lang.hitch(this, function(evt){
var cell = this.postGrid.cell(evt);
var post = cell.row.data;
if (cell.column.field === "title") {
post.title = evt.value;
} else if (cell.column.field === "text") {
post.text = evt.value;
} else if (cell.column.field === "category") {
post.category.value = evt.value;
}
this._updatePost(post);
}));
Instead of defining a renderCell function, define a get function (which is used to transform the value before it is even sent to renderCell) and a set function (which is used to transform data back before it's sent to a store when saving edits).
Something like:
get: function (object) {
return object.category.value;
},
set: function (object) {
return { value: object.category };
}
See also the documentation.

Kendo Grid - Dont allow certain records for editing

I have the below command button column in my Kendo grid..
How to disable the "Edit" button in the rows with empty "ItemValue".
$("#list485").kendoGrid({
dataSource: dataSource,
columns: [
{ command: [{ name: "edit" }], title: " ", width: "100px"},
{ field: "ItemValue", title: "Item Description" }
],
editable: "popup"
});
you may hide edit button by on dataBound function as below
dataBound: function (e) {
var grid = $("#list485").data("kendoGrid");
var gridData = grid.dataSource.view();
for (var i = 0; i < gridData.length; i++) {
var currentUid = gridData[i].uid;
if (gridData[i].ItemValue == "") {
var currenRow = grid.table.find("tr[data-uid='" + currentUid + "']");
var editButton = $(currenRow).find(".k-grid-edit");
editButton.hide();
}
}
}
i hope this will help you
Not sure if this can fulfill your need but it works fine for inline editing.
$("#list485").kendoGrid({
dataSource: dataSource,
columns: [
{ command: [{ name: "edit" }], title: " ", width: "100px"},
{ field: "ItemValue", title: "Item Description" }
],
editable: "popup",
edit: function(e) {
if(e.model.ItemValue == 100)//your condition
{
$("#grid").data("kendoGrid").refresh();
}
}
});
Anyway this is what I could able to find till now.
There must be some better solution for this.

Categories

Resources