When data is loaded into a DataTables object, it is assigned a row index - basically, it is added to an array structure. Rows are loaded in the order they are presented to DataTables - for example, when parsing a JSON source, or when loading the contents of a pre-populated HTML table:
|
|
So, Tiger Nixon is assigned to row index 0 internally in DataTables. This row index never changes, as long as the DataTables object exists and the row is not removed from the DataTables object.
We can use these indexes in various ways, for example:
|
|
Output:
Garrett Winters has internal row index 1
Ashton Cox has internal row index 2
If you want to find the row index of a specific row, you can use one of the following functions, depending on the object you are using (row, column, or cell):
For example, assume you have a click event defined on every <td>
cell in your table:
|
|
In this case the index()
call returns an object containing row
, column
, and columnVisible
fields. The row
value represents the internal DataTables row index.
There is also a column().index()
function which returns the column index (either the visible column index if columns can be hidden, or the original column index).
However, we may also want to know where a row is displayed in a table - its visual position, like a row number in a spreadsheet.
We may also need to take into account the fact that the row may not be on the current page (assuming DataTables pagination) - and not even part of the DOM. jQuery cannot help us in this case.
We can use the indexOf()
function to find the first occurrence of an item in a DataTables API object:
|
|
Output:
Cedric Kelly is at table row 10
Charde Marshall is at table row 11
Charde Marshall is at page 2 row 1
This example uses column( columnSelector, modifier )
, where:
columnSelector
is an integermodifier
is the object {order: 'current'}
In this case, the modifier is a DataTables selector-modifier
where current
means rows are processed in the order they are currently applied in the table (accounting for sorting and filtering).
Consider the following initComplete()
function:
|
|
This creates a JavaScript object containing an array of arrays (or an array of objects, depending on how your data was provided to DataTables).
The {order: 'index'}
selector ensures that the order of rows matches the original iternal index order.
You can also use {order: 'current'}
to capture your data with rows ordered as per the current display order.
If you use rows().data()
without a selector, then this defaults to using the display order.
Note that $( api.rows( {order: 'index'} ).data() )
creates a shallow copy of the table’s data. Changes to the DataTables data will be reflected in the tableData
object.
If you want a deep copy, you can use the jQuery extend()
function:
|
|