Reloading kendo ui grid the row item code executes an error - javascript

I've a web application with kendo ui grid. The grid is load with Bakbone.js when I click a button and I can remove a row with the next code:
$(document).on("click", "#grid tbody tr .ob-delete", function (e) {
var item = grid.dataItem($(this).closest("tr"));
var check = confirm("Do I delete:" + item.City );
if (check) {
grid.removeRow($(this).closest("tr"));
}
});
The cofiguration of the button to delete:
command: [
"edit", {
name: "destroy",
text: "Remove",
className: "ob-delete"
}]
When I reload the content (grid) pushing the button, if I want to delete a row, item.City produce an error.
The complete example here
Edited:
Solved here! Thanks to #Whizkid747!
To add in
command: [ "edit",{
//...
click: deleteRow
}]
Then, when button is clicked a function is called:
function deleteRow(e){
var item = this.dataItem($(e.currentTarget).closest("tr"));
var check = confirm("Do I delete:" + item.City );
if (check) {
grid.removeRow($(e.currentTarget).closest("tr"));
}
}

Not sure, but your grid is actually not the same grid but the old (before the reload) one and second grid is created.
Following line changed:
var item = $('#grid').data().kendoGrid.dataItem($(this).closest("tr"));
updated version.
I suggest you to just change the data through the dataSource.data() method instead of recreating the Grid. Or change your logic so you actually destroy the widget before recreating it.

Related

How to disable a custom DataTables button in its action callback?

This is in a C# ASP.NET MVC 5 web application, using DataTables version 1.10.22.
I configure a DataTable to have a custom button. The action for the button is a callback function. After that function executes once, I want to disable the button.
I can disable all buttons associated with the DataTable. But, how do I disable just one button?
The DataTables documentation, such as https://datatables.net/reference/api/buttons().disable(), has an example that seems to identify certain buttons by... their CSS class name?
var table = $('#myTable').DataTable();
var buttons = table.buttons( ['.edit', '.delete'] );
buttons.disable();
But, how do I uniquely identify my custom button?
The action callback function for the button seems to be provided with several parameters that represent the button. But, the node does not seem to have a disable() function. Changing config.enabled to false has no effect. What else can I try?
The following is what I am trying to do in my Views/Foo/Index.cshtml:
<script>
$( document ).ready( onReady );
function onReady()
{
var config = {};
config.buttons =
[
// A button to create data for the table.
{
text: '<span class="fa fa-plus"/>',
titleAttr: 'Create states',
action: createStates,
enabled: true,
}
... other buttons ...
];
... other configuration ...
$( '#state-table' ).DataTable( config ) );
}
/**
* Create the states.
*
* Parameters:
* e (object): The event.
* table (object): The DataTable.
* node (jQuery): The jQuery instance of the button that was clicked.
* config (object): The button configuration.
*/
function createStates( e, table, node, config )
{
//------------------------------
// Create client-side state data in the table.
table.clear();
for ( var i = 0; i < 3; i++ )
{
var data = { Id: i, Name: 'state ' + i };
table.row.add( data );
}
//------------------------------
// Calling draw() at the end updates the DataTable internal caches.
table.rows().draw();
//------------------------------
// Disable the button, so that states cannot be created again.
// *** How ? ***
// Just changing this property has no effect on the button.
config.enabled = false;
// This disables all buttons, not just the one I want.
table.buttons().disable();
}
</script>
Each DataTables button can be given a button name and/or a class name - and then you can refer to that button using either of these - for example:
$(document).ready(function() {
var table = $('#myTable').DataTable( {
dom: 'Bfrtip',
"buttons": [
{
text: 'My Button',
className: 'myButtonClass',
name: 'myButtonName'
}
]
} );
table.buttons( '.myButtonClass' ).disable();
//table.buttons( 'myButtonName:name' ).disable();
});
In the above example, the button has both a button name and a class name.
There are various additional ways to select one or more buttons:
buttons( selector );
These selector options are documented here.
And, yes, that example in your question...
var buttons = table.buttons( ['.edit', '.delete'] );
...is indeed using the class name selector.

Button click in kendo grid column firing onclick of whole row

Our customer wanted a kendo grid where he can click anywhere on a row to open the corresponding detail page. I'm adding the rows like this:
const cols = [
{ field: "Date", title: "Date", template: "#=kendo.toString(kendo.parseDate(Date, 'yyyy-MM-dd), 'dd.MM.yyyy')#" },
{ field: "Title", title: "Title" },
{ field: "", command: ["destroy"], title: " " }];
let grid = $("#grid").kendoGrid({
dataSource: this.dataSource,
pageable: true,
filterable: true,
sortable: true,
columns: cols,
editable: "detail"
}).data("kendoGrid");
grid.one("dataBound", this.onDataBound.bind(this));
And in my function onDataBound():
const grid = $("#grid").data("kendoGrid");
$(grid.tbody).on("click", "tr", function (e) {
const rowData = grid.dataItem(this);
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
});
This works perfectly as expected. However, as you see, I have a column with a delete button. Here is the problem. Whenever I click on the delete button, I'm getting the confirmation message ("Are you sure to delete [...]?") and actually can delete the row successfully, but the detail page of the row opens as soon as I click the button.
How can I let the row know that it shouldn't open the detail page when I click the delete button?
You should use e.stopPropagation(); on delete button so it will not pass the event to the row also.
I've found a solution. I can check the tagName when binding the click function to the row:
$(grid.tbody).on("click", "tr", function (e) {
if (e.target.tagName == "TD") {
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
}
});
When I click the button, tagName get either "SPAN" or "A". Everything outside the button results in "TD".

How can I get selected row data in kendo

I'm using this context menu example.
I used the context menu select event like this:
menu = $("#menu").kendoContextMenu({
target: "#listview-context-menu",
filter: ".product",
animation: {
open: { effects: "fadeIn" },
duration: 500
},
select: onSelect
});
function onSelect(e) {
console.log(e);
}
It's working fine, but now I'm getting the current menu object. How can I get selected row data instead?
For example, I have right-clicked on "RE: New version of Telerik Trainer (1st one record)" and then click on reply to sender, so how can I get row object of current row.
You can get the reference to the datarow by using the snippet below
function onSelect(e) {
var lst =$("#listview-context-menu").getKendoListView();
var row = lst.dataItem(e.target);
console.log(row);
}
Please refer the fiddle here for a demo

EXtJS grid CheckColumn, How to execute function, after column is clicked/its state is checked?

I have ExtJS GRID with checkcolumn, which is declared this way:
// the check column is created using a custom plugin
sel_column = new Ext.grid.CheckColumn({
sortable: false,
header: 'STE<br />SEL',
dataIndex: 'sel',
width: field_w,
listeners:
{
"mousedown":
{
fn : function(e)
{
$.log( "Sel cellclick" , e );
}
}
}
});
I want add some listener on changfe of it stae, or on mouse click.
Finaly - want id's of rows, where i click this column - to be stored in text field
For now i can understood how to catch click event, i use onMouseDown, this way:
// the check column is created using a custom plugin
sel_column = new Ext.grid.CheckColumn({
sortable: false,
header: 'STE<br />SEL',
dataIndex: 'sel',
width: field_w,
onMouseDown: function( e )
{
$.log( e,"MouseDown" );
}
});
But it fires, when i click ANY cell, not only checkboxed ...
Pls help me
checkbox plugin need modification, after which it can fire click event.
/*
**************************************************************
Sample to add event 'checkchange' in checkbox on checkcolumn,
works with ExtJS 4 or above
*/
//Add you checkcolumn id:'op_check'. No need separate plugin.
//Put this code in You Grid
listeners:{
afterrender:function(){
g = this; //This grid
Ext.getCmp('op_check').on('checkchange', function(c, i){
//Get id from row/record (if in store exist field 'id')
//"i" - in this function is index row, where clicked checkbox
rec = g.store.getAt(i);
id = rec.get('id');
console.log(id); //:)
});
}
}

jqGrid with an editable checkbox column

When using jqGrid how do you force a cell to load in its editable view on page load as well as when it is clicked?
If you set up 'cell editing' like below, the check box only appears when you click on the cell.
{ name: 'MyCol', index: 'MyCol', editable:true, edittype:'checkbox', editoptions: { value:"True:False" },
cellEdit:true,
Also on clicking checkbox, is there a way of sending a AJAX post to server instantly rather than having to rely on the user pressing enter?
To allow the checkboxes to always be click-able, use the checkbox formatter's disabled property:
{ name: 'MyCol', index: 'MyCol',
editable:true, edittype:'checkbox', editoptions: { value:"True:False"},
formatter: "checkbox", formatoptions: {disabled : false} , ...
To answer your second question, you will have to setup an event handler for the checkboxes, such that when one is clicked a function is called to, for example, send an AJAX POST to the server. Here is some example code to get you started. You can add this to the loadComplete event:
// Assuming check box is your only input field:
jQuery(".jqgrow td input").each(function(){
jQuery(this).click(function(){
// POST your data here...
});
});
This is an old one but has a lot of view so I decided to add my solution here too.
I'm making use of the .delegate function of JQuery to create a late binding implementation that will free you from the obligation of using the loadComplete event.
Just add the following:
$(document).delegate('#myGrid .jqgrow td input', 'click', function () { alert('aaa'); });
This will late bind that handler to every checkbox that's on the grid rows.
You may have a problem here if you have more than one checkbox column.
I had the same problem and I suppose that I found a good solution to handle checkbox click immediately. The main idea is to trigger editCell method when user clicks on the non-editable checkbox. Here is the code:
jQuery(".jqgrow td").find("input:checkbox").live('click', function(){
var iRow = $("#grid").getInd($(this).parent('td').parent('tr').attr('id'));
var iCol = $(this).parent('td').parent('tr').find('td').index($(this).parent('td'));
//I use edit-cell class to differ editable and non-editable checkbox
if(!$(this).parent('td').hasClass('edit-cell')){
//remove "checked" from non-editable checkbox
$(this).attr('checked',!($(this).attr('checked')));
jQuery("#grid").editCell(iRow,iCol,true);
}
});
Except this, you should define events for your grid:
afterEditCell: function(rowid, cellname, value, iRow, iCol){
//I use cellname, but possibly you need to apply it for each checkbox
if(cellname == 'locked'){
//add "checked" to editable checkbox
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked',!($("#regions").find('tr:eq('+iRow+') td:eq('+iCol+') input:checkbox').attr('checked')));
//trigger request
jQuery("#grid").saveCell(iRow,iCol);
}
},
afterSaveCell: function(rowid, cellname, value, iRow, iCol){
if(cellname == 'locked'){
$("#grid").find('tr:eq('+iRow+') td:eq('+iCol+')').removeClass('edit-cell');
}
},
Then your checkbox will send edit requests every time when user clicks on it.
I have one submit function that sends all grid rows to webserver.
I resolved this problem using this code:
var checkboxFix = [];
$("#jqTable td[aria-describedby='columnId'] input").each(function () {
checkboxFix.push($(this).attr('checked'));
});
Then I mixed with values got from the code below.
$("#jqTable").jqGrid('getGridParam', 'data');
I hope it helps someone.
I had shared a full code at the link below, you can take a look if you need it.
http://www.trirand.com/blog/?page_id=393/bugs/celledit-checkbox-needs-an-enter-pressed-for-saving-state/#p23968
Better solution:
<script type="text/javascript">
var boxUnformat = function ( cellvalue, options, cell ) { return '-1'; },
checkboxTemplate = {width:40, editable:true,
edittype: "checkbox", align: "center", unformat: boxUnformat,
formatter: "checkbox", editoptions: {"value": "Yes:No"},
formatoptions: { disabled: false }};
jQuery(document).ready(function($) {
$(document).on('change', 'input[type="checkbox"]', function(e){
var td = $(this).parent(), tr = $(td).parent(),
checked = $(this).attr('checked'),
ids = td.attr('aria-describedby').split('_'),
grid = $('#'+ids[0]),
iRow = grid.getInd(tr.attr('id'));
iCol = tr.find('td').index(td);
grid.editCell(iRow,iCol,true);
$('input[type="checkbox"]',td).attr('checked',!checked);
grid.saveCell(iRow,iCol);
});
});
</script>
In your colModel:
...
{name:'allowAccess', template: checkboxTemplate},
...

Categories