Shanmugapriya
Shanmugapriya

Reputation: 57

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);
                            });

Upvotes: 2

Views: 8083

Answers (2)

MyChickenNinja
MyChickenNinja

Reputation: 31

To build on davidkonrad's answer, but keeping the function to datatables:

    let table = $('#example').DataTable({
        "ajax": {
            //Do your ajax stuff to get your data
        },
        initComplete: function () {
            //After the ajax has run, initComplete can get the total count of lines .
            console.log(table.data().count())
        }
    });

This was the only thing that worked for me.

Keep in mind that this only works on the content within the currently loaded table. If you use pagination, you're going to need to make an additional call to your backend.

Upvotes: 0

davidkonrad
davidkonrad

Reputation: 85578

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/

Upvotes: 6

Related Questions