Note: I will be hiding the data column and hence I have to use jQuery Datatable API.
For my jQuery Datatable, each row have a button beside it. The purpose of the button is to retrieve the column data. The column data will be hidden.
For my button click event, this is my code.
$('#Table').on('click', '.Button', function () {
var tr = $(this).closest("tr");
var rowindex = tr.index();
//Get row based on index
var rowData = $("#Table").DataTable().row(rowindex).data();
var data = rowData.Data;
});
This code is working, however there is one problem.
It is not able to retrieve the data of the sorted column.
For example, before Sorting,
Row 1 - Index 0 Data - A
Row 2 - Index 1 Data - B
After sorting,
Row 2 - Index 0 Data - B
Row 1 - Index 1 Data - A
Clicked on Data B row button,
Data Gotten: A
Hopefully I have explained my problem clear enough. Thanks!
Updated Fiddle: https://jsfiddle.net/mt4zrm4b/3/
Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.
Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
You need to pass in your selector tr
as the rowSelector
parameter for row()
.
DOM elements can be given as a row selector to select a row in the DataTabels API from that DOM element. This can be useful for getting data from a row, or performing other row based operations, when you have only the DOM node for reference, for example in an event handler.
The reason is because if you were to sort, the row indexes that DataTables doesn't get updated. It's recommended to select the row via your tr
, like this:
$('#Table').on('click', '.Button', function() {
var tr = $(this).closest("tr");
// Get row based on tr instead.
var rowData = $("#Table").DataTable().row(tr).data();
var data = rowData.Data;
alert(data);
});
See this updated fiddle for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With