How to get the total number of rows in DataTables using Jquery in JSP

I am using a datatable in my application. When loading the page i need to display the number of rows of the table in a span. I am using table.data().count() to get the count of the rows. But its not giving correct value.

JSP:

<table id="example" class="" cellspacing="0" width="100%" style="padding: 10px">
<thead>
    <tr>
        <!-- <th>S No</th> -->
        <th>Doc Id</th>
        <th id="Position">Geo</th>
        <th id="Position">Practice</th>
        <th id="Position">Opportunity Id</th>
        <th id="Position">Reference Id</th>
        <th id="Position">Status</th>
    </tr>
</thead>
<tbody>
</tbody>
</table>

Jquery:

var table = $('#example').DataTable();
$(document).ready(function() {
                            var rowCount = table.data().count();
                            alert(rowCount);
                            });

Answers 1

  • First of all, you cannot rely on ready() being executed after the table is initialised. It is rare the ready() construct is actually needed or even useful, and when people think they need it, it is often the side effect of bad design. I have literally seen hundreds of posts here on SO where people have problems caused by peculiar nested ready() scopes, and most of the times the only reason for the use of ready() is "tradition" or "just to be sure", i.e cargo cult programming.

    Secondly there is no count() method on data(). There is, but this is because data() in fact is returning an API, the data as an array with API methods attached.

    So use Array.length to get the number of rows, and place the code inside dataTables initComplete callback :

    var table = $('#example').DataTable({
       initComplete: function() {
          $('#count').text( this.api().data().length )
       }
    })  
    

    the markup could look like this :

    <p id="count"></p>
    

    http://jsfiddle.net/f9zq9gn8/


Related Articles