Search code examples
jquerydatatables

fnFilter value 'Active' not working


I'm having trouble with searching a DataTable programmatically for the string 'Active'. If I change my table to say 'ActiveTest', the fnFilter works fine and filters it down properly. However it does not seem to work with the string 'Active'. Anyone have any ideas as to why?

Also, is there any programmatic way to filter down the table to only columns which have a specific value without showing that value in the Search input box? I'd rather have a checkbox on my page that says "Show Active Only" which would filter it down and then still allow the user to filter more using the Search box.

Here is how I am trying to filter down the table now

$('#selector').dataTable().fnFilter('Active');

This causes the Search input box to show 'Active', but nothing happens. This works fine with other strings in the table, but it looks like the string 'Active' is reserved or something because it just doesn't filter. Even if I type manually into the search box 'Active' it still does not filter.

Snippet provided as example

$('#mytable').DataTable();

$('#testbutton').on('click', function(e) {
     $('#mytable').dataTable().fnFilter('Active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<table id="mytable">
  <thead>
    <tr>
      <th>name</th>
      <th>status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>john doe</td>
      <td>Active</td>
    </tr>
    <tr>
      <td>jane doe</td>
      <td>Inactive</td>
    </tr>
  </tbody>
</table>

<input type="button" id="testbutton" value="filter" />

Thank you!


Solution

  • The problem is that the word "Inactive" includes the string "active", and by default, fnFilter() does not search for whole words only and does a case-insensitive search. You can verify this by changing the text "Inactive" instead:

    $('#mytable').DataTable();
    
    $('#testbutton').on('click', function(e) {
         $('#mytable').dataTable().fnFilter('Active');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
    <table id="mytable">
      <thead>
        <tr>
          <th>name</th>
          <th>status</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>john doe</td>
          <td>Active</td>
        </tr>
        <tr>
          <td>jane doe</td>
          <td>Foo</td>
        </tr>
      </tbody>
    </table>
    
    <input type="button" id="testbutton" value="filter" />

    You have at least two options to solve this:

    • You can enable case-sensitive matching (6th parameter, boolean) if that's enough for your needs
    • You can enable regex (3rd parameter, boolean) and use word-boundaries to match only whole words