Timebreaker900
Timebreaker900

Reputation: 332

Datatables count rows only in a specific column

I want to count all rows inside a column with the output idea.

I tried this:

alert('Rows: ' + table.column(1).rows(':contains("idea")').count());

the .column(1) doesn't seem to work because it also counts other columns.

Example of the DataTable

Column0  | Column1
------------------
blahidea | error
blah     | idea 
blah     | idea
blah     | error

the alert will count 3 and not 2! What do I need to change that it counts only 2?

Upvotes: 1

Views: 2538

Answers (1)

User863
User863

Reputation: 20039

Using search() and rows()

var table = $('#example').DataTable()

var length = table
              .column(1)
              .search('idea')
              .rows({ search: 'applied'})
              .count()

console.log(length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />


<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Column0</th>
      <th>Column1</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>blahidea </td>
      <td>error</td>
    </tr>
    <tr>
      <td>blah </td>
      <td>idea </td>
    </tr>
    <tr>
      <td>blah </td>
      <td>idea </td>
    </tr>
    <tr>
      <td>blah </td>
      <td>error </td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions