Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datatables row count across pages

I'm using the jQuery DataTables plug-in for my HTML table.

Is there a way to get the row count of the number of rows in my table across pages.

For example, if I have 70 rows in my table, and let's say 50 of them get displayed on the 1st page, and 20 on the 2nd page. Is there a way to get the count of 70?

I've tried all the suggestions included in this post: jQuery: count number of rows in a table

This includes:

var rowCount = $('#myTable tr').length;
var rowCount = $('#myTable tr').size();
var rowCount = $('#myTable >tbody >tr').length;
var rowCount = $("#myTable").attr('rows').length;

But all the above suggestions seem to return the number of rows on the existing page (in this case, 50 and not 70).

like image 772
Pritish Avatar asked Jul 13 '10 14:07

Pritish


3 Answers

It looks like DataTables is removing the rows that aren't on the current page from the DOM, so you aren't going to be able to count them with a jQuery selector. You'll have to use the DataTables API, specifically the fnGetData function:

$(document).ready(function() {

    // Initialize your table
    var oTable = $('#myTable').dataTable();

    // Get the length
    alert(oTable.fnGetData().length);
} );
like image 152
Matt Peterson Avatar answered Oct 16 '22 05:10

Matt Peterson


SOLUTION

For DataTables 1.10

Use page.info() to retrieve information about the table as shown below.

Property recordsTotal will hold total number of records in the table.

var table = $('#example').DataTable({
    "initComplete": function(settings, json){ 
        var info = this.api().page.info();
        console.log('Total records', info.recordsTotal);
        console.log('Displayed records', info.recordsDisplay);
    }
});

DEMO

See this jsFiddle for code and demonstration.

NOTES

This solution will work for both client-side and server-side processing modes as long as you use page.info() once data has been retrieved, for example in initComplete callback function.

like image 35
Gyrocode.com Avatar answered Oct 16 '22 05:10

Gyrocode.com


When using server-side paging you can access the total record count like so...

dt.fnSettings()._iRecordsTotal;

If you're using server side paging, you could hook into the fnDrawCallback and update your html whenever the table is drawn...

$('#Table').dataTable({
    "fnDrawCallback": function (oSettings) {
        alert(oSettings._iRecordsTotal);
     }
});
like image 38
dotjoe Avatar answered Oct 16 '22 05:10

dotjoe