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

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.

Related

How to get the data inside a html table cell when clicked on it?

I created a html table and filled it dynamically. So I want to alert the data inside a cell of the table when i clicked it. Here is the code for the table
JSP
<table id="load-opt"></table>
I'm filling the data inside dynamically like this
var fillTable = function($element, data) {
var t_head = $("<tr></tr>");
for(var ind=0; ind<data.length; ind++) {
//name is the name and desc is the description for each option
var $option = $("<tr></tr>");
$option.html("<td>"+name+"</td><td>"+desc+"</td>");
}
};
I tried this but it's not working, it's giving "undefined".
var choice = $('table#load-opt tr td');
choice.click(function(){
alert(choice); // also tried alerting choice.textContent, choice.innerHTML and choice.firstChild
});
you are actually trying to alert the 'td' object not value of from that object so you can use following to solve the query.Here i am using on instead of direct click function because of dynamically added data.
var choice = $('table#load-opt tr td');
choice.on('click', function(){
alert($(this).text());
});
You can use $(this).text() to fetch the data in table cell.
This is a link.

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

Kendo grid - get current editing row

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

javascript editable table does not work properly

I am using the following code to make a html table editable (this code is obtained from an online tutorial link: http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425).
$("td").dblclick(function () {
//Obtain and record the value in the cell being edited. This value will be used later
var OriginalContent = $(this).text();
//Addition of class cellEditing the cell in which the user has double-clicked
$(this).addClass("cellEditing");
//Inserting an input in the cell containing the value that was originally on this.
$(this).html("<input type='text' value='" + OriginalContent + "' />");
//directing the focus (cursor) to the input that was just created, so that the user does not need to click on it again.
$(this).children().first().focus();
//the opening and closing function that handles the keypress event of the input.
//A reserved word this refers to the cell that was clicked.
//We use the functions first and children to get the first child element of the cell, ie the input.
$(this).children().first().keypress(function (e) {
//check if the pressed key is the Enter key
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
It seems to work fine. Then I am using the following function to read the contents of the table and create a json representation:
function showRefTable(){
var headers = [];
var objects = [];
var headerRow = $('#dataTable thead tr');
var rows = $('#dataTable tbody tr');
headerRow.find('th').each(function(){
headers.push($(this).text());
});
for (var i=0; i<rows.length; i++){
var row = rows.eq(i);
var object = new Object();
for (var j=0; j<row.find('td').length; j++){
object[headers[j]] = row.find('td').eq(j).text();
}
objects.push(object);
}
var json = JSON.stringify(objects);
alert(json);
}
This function is used as a callback to an onclick event.
The problem is that the function used to read the table contents shows the original contents even if I make an edit (show page source shows the original content).
Thanks
It's really bad to read table contents from .text(). You will not be able to use any formatting for numbers and many other problems. You'd better of keeping table contents in standalone datasourse object and redrawing table from it every time when user changes values.
I would advise using kendo grid - it's powerfull, reliable js table.
EDIT: your function does not work, becuse you said you call it as callback to onclick event. So you read contents of the table before they actually changed.
You should read contents when they are saved. In your case, try calling you function when user saves the input (presses Enter)
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
//Now, when content is changed, call your function
showRefTable();
}

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