Kendo grid - get current editing row - javascript

How do you get the current row that's been edited even when it's not selected? I have a batch enabled Kendo grid that is navigatable. My goal is to manually edit data in a column using the dataItem.set() method. However, when you add a row it does not get selected automatically. Hence, vm.testGrid.dataItem(vm.testGrid.select()) cannot be used.
vm.testGrid.dataSource.get(e.model.get("Id")) gets the newly added row, but if multiple rows were added before saving, it will always get the first added row ("Id" is set to auto increment and is automatically generated by the database server, therefore all newly created rows will initially have 0 before saving).
vm.onEdit = function (e) {
$('input.k-input.k-textbox').blur(function (f) {
//var data = vm.testGrid.dataItem(vm.testGrid.select());
var data = vm.testGrid.dataSource.get(e.model.get("Id")); // will always get the firstly added row
data.set("LookupCol", "1000");
}
});
Is there a better solution to get the row that's been currently edited? Or is there a better way to edit the current row?

The following will give you the data item associated with the current cell:
var dataItem = grid.dataItem(grid.current().closest("tr"));
// You can then set properties as you want.
dataItem.set("field1", "foo");
dataItem.set("field2", "bar");

I used the JQuery closest() function:
vm.onEdit = function (e) {
$('input.k-input.k-textbox').blur(function (f) {
var data = vm.testGrid.dataItem($(e.container).closest("tr"));
data.set("LookupCol", "1000");
}
});

You can also write an extension for the grid, e.g. like this
// extend the grid
kendo.ui.Grid.fn.getCurrentDataItem = function() {
var that = this, current = that.current(), dataItem = null;
if (current) {
dataItem = that.dataItem(current.closest('tr'));
}
return dataItem;
}
JSFiddle example

Related

Multiple Tables on Datatables with different option

I have multiple table (tbUser, tbRole, tbJob) and i want to make my code simple.
this is what i done before:
var userTable = $('#tbUser').DataTable();
var roleTable = $('#tbRole').DataTable();
var jobTable = $('#tbJob').DataTable();
Each tables has different options, columns and have one thing in common has column [action] to put View/Edit/Remove button. Is there a simple way to do jquery event click action button in each table.
This is my code:
$('#tbUser tbody').on('click', '#btn_edit', function (e) {
let index = $(this).parents('tr');
let data = userTable.row(index).data();
/** Something */
});
/** REPEAT EACH TABLE */
and I've tried :
$('table tbody').on('click', '#btn_edit', function (e) {
let index = $(this).parents('tr');
let data = userTable.row(index).data(); //===> But how to change table dynamicly on this line
/** Something */
});
Firstly your edit button needs to be targetted using a class not an ID, otherwise it will only ever find the first button.
Create an object that holds a reference to each of your tables. I'm using the table id as the key, and the instantiated datatable as the value.
const tables = {
tbUser: userTable,
tbRole: roleTable,
tbJob: jobTable
}
Then with your button click, identify which table it is part of and use that to grab the table instantiation from the object you created earlier
$('table tbody').on('click', '.btn_edit', function (e) {
const tableId = this.closest('table').id;
const datatable = tables[tableId];
const index = $(this).parents('tr');
const data = datatable.row(index).data();
/** Something */
});

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:
https://jsfiddle.net/4fr3edk7/2/
If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.
This code snippet loops through each key, then loops through each value of that key:
for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){
$("#input1").val(getval[0]);
$("#input2").val(getval[1]);
}
}
How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.
First, as mentioned by #Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.
Updated Fiddle
This function will get the values of the form and will store in on a global object
function setMap(id){
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
globalchanges[id] = [firstrow,secondrow];
}
This other function will check if the global object has values for the passed id, if not, it will use the values on the row
function getMap(id, tr){
if(globalchanges[id] != undefined && globalchanges[id].length == 2){
$("#input1").val(globalchanges[id][0]);
$("#input2").val(globalchanges[id][1]);
}
else{
$("#input1").val($(tr).find('td').eq(1).text());
$("#input2").val($(tr).find('td').eq(2).text());
}
}
Please note there are also changes on the dbclick and click events, they should be separated
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$('#id').val(id);
getMap(id,this);
});
$("#savebtn").click(function(){
var id = $('#id').val();
setMap(id);
});
And that we added and additional input to store the id on the form.
You are going to need to rethink your logic because of this part
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
$("#savebtn").click(function(){
addToMap(id);
});
});
-Every time- you double click a table row you are adding a new click binding to the savebtn element. This means if you double click both rows, when you click that button it will execute addToMap for both ids. You may have other issues with your logic relying on only two other inputs for multiple rows, but this double/triple/+ binding is going to bite you.
There are few changes required in your logic as well as implementation.
1: Do not bind save event inside row click.
2: You are selecting the value in row double click event from td element. You need to update this element to keep your logic working
3: Keep track of which row is getting updated.
Updated Code
var globalchanges = {};
var rowSelected = null;
$("#table tr").dblclick(function() {
$("#txtbox-wrapper").css({
"display": "block"
});
rowSelected = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
});
$("#savebtn").click(function() {
addToMap(rowSelected);
});
function addToMap(row) {
var array = [];
var changes = {};
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
array.push(firstrow, secondrow);
globalchanges[row] = array;
makeChanges(row);
}
function makeChanges(row) {
var key = Object.keys(globalchanges);
console.log(key);
$("#table tr td").each(function(k, v) {
if ($(v).text() == key) {
$(v).next().html(globalchanges[row][0]);
$(v).next().next().html(globalchanges[row][1]);
globalchanges = {};
}
});
}
Working fiddle : https://jsfiddle.net/yudLxsgu/

Select programmatically Kendo grid row

I found posts with similar titles but I still cannot resolve my issue. Definitely I am doing something wrong.
In Kendo grid configuration have some function which take context (grid) and read selected row:
change: function (e) {
refresh(this);
}
This is how I configured "change" event.
In function "refresh(grid)" I am getting selected row on following way:
refresh: function (grid) {
var selectedRows = grid.select();
var selectedRow = grid.dataItem(selectedRows[0]);
var id = selectedRow.Id;
}
This approach works perfect when I select grid row manually. But when I select row programatically "selectedRow" variable is null.
I am selecting programatically on following way:
var grid = $("#grid").data("kendoGrid");
var rows = grid.dataSource.data();
var row = rows[rows.length - 1];
grid.select(row);
As I sad in above, in previous "refresh(grid)" method variable selectedRow will be null.
Does anybody have some opinion about that? Why is it happened?
Thanks
According to the Grid documentation the "select" method accepts "string" parameter (selector) or jQuery element. That why if you need to correctly select the row you should modify your current code as follows:
var grid = $("#grid").data("kendoGrid");
//if you are using the "pageable" option of the grid
//you should get the visible rows using the .view() method
var models = grid.dataSource.data();
var model = models[models.length - 1];
var lastRowUid = model.uid;
//find the target row element:
var row = grid.table.find("[data-uid=" + lastRowUid + "]");
grid.select(row);

How to get selected row index from jquery datatables without using TableTool

I need to get the row id or index of user selected rows from jquery datatables without using the TableTool. Once I get the indexes or the Ids, I will use them to select these rows after the user comes back to the same page. How do I get the row Id or index of the select rows? Many thanks !
JSP code:
// when a row is selected, I want to get the row id or index
$('#userTable tbody tr').on('click', function()
{
var oTable = $('#userTable').dataTable();
var data = oTable.fnGetData(this);
selectedRowId = data[4];
alert(selectedRowId); // this printed "undefined"
var rowIndex = oTable.row(this).index();
alert(rowIndex); // this alert didn't even get invoked.
});
var rowIndex = oTable.row(this).index();
The above will work but you have to use:
var oTable = $('#userTable').DataTable();
which will return the API and should allow you to use row(this).index()
Instead Of:
var oTable = $('#userTable').dataTable();
However without seeing a working copy of the code (JSFiddle maybe) I am unsure why the fnGetData() is not working.

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Categories

Resources