jQuery DataTables - get page of a given row
I ended up writing a small dataTable plugins for it:
// get the page of a given item in order to paginate to it's page on load
$.fn.dataTableExt.oApi.fnGetPageOfRow = function (oSettings, iRow) {
// get the displayLength being used
var displayLength = oSettings._iDisplayLength;
// get the array of nodes, sorted (default) and using current filters in place for all pages (default)
// see http://datatables.net/docs/DataTables/1.9.beta.1/DataTable.html#%24_details for more detals
var taskListItems = this.$("tr", { "filter": "applied" });
// if there's more than one page continue, else do nothing
if (taskListItems.length <= displayLength) return;
// get the index of the row inside that sorted/filtered array
var index = taskListItems.index(iRow);
// get the page by removing the decimals
var page = Math.floor(index / displayLength);
// paginate to that page
this.fnPageChange(page);
};
Pass in the iRow and it'll paginate to that item's page.
I've written a function to move you to the page with the given row. However, it uses newer API. The part inside the if is what you want.
function moveToPageWithSelectedItem() {
var numberOfRows = itemsTable.data().length;
var rowsOnOnePage = itemsTable.page.len();
if (rowsOnOnePage < numberOfRows) {
var selectedNode = itemsTable.row(".selectedItem").node();
var nodePosition = itemsTable.rows({order: 'current'}).nodes().indexOf(selectedNode);
var pageNumber = Math.floor(nodePosition / rowsOnOnePage);
itemsTable.page(pageNumber).draw(false); //move to page with the element
}
}
In 1.10 you could simply do:
table.rows( { order: 'applied' } ).nodes().indexOf( ... );
Assuming you are working with a tr
node.
edit - sorry that gets the position in the data set. You would need to use the information from page.info().len
to then divide that index and get the page number.