Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the total number of occurrences of a word in DataTables

I want to know the number of times a word appears in my table (DataTables)

var numberOccurence = $('tr > td:nth-child(2):contains("'+ word +'")').length;

The problem is that it looks only on the visible part of the table, that is, if there are 10 pages on DataTables, it only gives me the number of occurrences on the first page

How to do it?

EDIT Here is the Html

<div class="table-row">
  <div class="table-responsive">
    <table id="fileTable" class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>Date</th>
          <th>Localisation</th>
          <th>User</th>
          <th>Like</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($orders as $order) { ?>
        <tr>
          <td><?= $order['date'] ?></td>
          <td><?= $order['localisation'] ?></td>
          <td><?= $order['user'] ?></td>
          <td><?= $order['like'] ?></td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
  </div>
</div>
like image 285
Rocstar Avatar asked Jan 29 '26 13:01

Rocstar


2 Answers

Assuming that you are using DataTables plugin, you could search the data of DataTable using data()

// Column name to search
var colName = 'columnName';
// Column index to search
var colIndex = 2;

var term = 'word';

// Get reference of DataTables API
var tbl = $('#myTable').DataTable();

// Get data (array of rows)
var data = tbl.data();

// Use filter function to search for term
var occurence = data.toArray().filter(function(row) {
   // If data is array of objects
   return row[colName].indexOf(term) !== -1;
   // If data is array of strings
   return row[colIndex].indexOf(term) !== -1;
}).length;

You can check the documentation about data()

like image 137
kapantzak Avatar answered Feb 01 '26 00:02

kapantzak


You are close, but use the $ API method along with the :contains selector instead :

var count = table.$('td:contains("'+ term +'")').length;

demo -> http://jsfiddle.net/mLqreyfg/

$() : Perform a jQuery selection action on the full table

like image 32
davidkonrad Avatar answered Feb 01 '26 01:02

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!