15

I am using jQuery DataTables (http://www.datatables.net/) to display some tabular data. The search/ filter is a powerful feature. Although if multiple keywords are searched in the table the search filters only the already filtered data.

For instance in the example here - http://jsfiddle.net/illuminatus/2j0Lz5or/1/

If the keywords are searched like 10 99 it does not yield any result. I want the search to display all the results/ rows containing all the keyword which are searched or entered.

Searching 10 99 would display rows 1, 5 and 6.

Technically, the search should be an 'OR' search.

Would appreciate any help.

EDIT: The search should be an 'OR' search.

1

4 Answers 4

20

AND-filter (include rows where all search words is present). This custom filter overrides the builtin filtering process. Each column in each row is compared with each search word.

$.fn.dataTableExt.afnFiltering.push(
  function(oSettings, aData, iDataIndex) {
      var keywords = $(".dataTables_filter input").val().split(' ');  
      var matches = 0;
      for (var k=0; k<keywords.length; k++) {
          var keyword = keywords[k];
          for (var col=0; col<aData.length; col++) {
              if (aData[col].indexOf(keyword)>-1) {
                  matches++;
                  break;
              }
          }
      }
      return matches == keywords.length;
   }
);

forked fiddle -> http://jsfiddle.net/9d097s4a/


OR-filter (include rows where at least one of the search words is present). This is another approach, mostly an attempt to streamline this answer above. Instead of playing with oSearch and hardcoded search terms, the default filtering event is replaced with an event that tokenizes the search phrase and then performs an advanced fnFilter(). As optional experiment, the search is now only performed when the user hits enter - it feels somehow more natural.

var input = $(".dataTables_filter input");
input.unbind('keyup search input').bind('keypress', function (e) {
    if (e.which == 13) {
       var keywords = input.val().split(' '), filter ='';
       for (var i=0; i<keywords.length; i++) {
           filter = (filter!=='') ? filter+'|'+keywords[i] : keywords[i];
       }            
       dataTable.fnFilter(filter, null, true, false, true, true);
       //                                ^ Treat as regular expression or not
    }
});

see demo -> http://jsfiddle.net/2p8sa9ww/

14
  • Thanks for your prompt response. Although, your forked fiddle is not working as expected. If I search for 10 99 the search should yield rows 1, 5 and 6. Aug 19, 2014 at 13:16
  • 2
    hey @SameerJoshi, well - if you expect rows 1,5 and 6 to be returned on 10 99, then it is not an AND search you want to perform, but a OR search? No rows matches both 10 and 99. Aug 19, 2014 at 13:30
  • My bad. You are correct. I need an 'OR' search not an 'AND'. I have edited the question accordingly. Any idea how this can be managed? Aug 20, 2014 at 3:45
  • 1
    @Borna, If I understand you correct, then you should use aData[col].charAt(0) == keyword.charAt(0) (or something similar, if you want to test on the first character) I dont know how excatly yajra dataTables output the javascript clientside, but it is jQuery dataTables and there should be no difference what so ever in how the plugin works, yajra dataTables is just a convenient wrapper for the plugin. Aug 24, 2016 at 10:02
  • 1
    @davidkonrad Apologies I realized after some more testing that it is in fact changing the search field. No help needed now but thank you. Just trying to get fnfilter() working in the newest DataTables.
    – Chisx
    Aug 15, 2017 at 20:05
7

Updated for Datatables 1.10

//Search field in new location

Table = $('#your_datatable').DataTable();
$('#your_input_text_field').keyup(function () {
    Table.search($(this).val()).draw();
})

////OR search (enabling regular expression search)
var input = $('#your_input_text_field');
input.unbind('keyup search input').bind('keypress', function (e) {
    if (e.which == 13) {
        var keywords = input.val().split(' '),
            filter = '';
        for (var i = 0; i < keywords.length; i++) {
            filter = (filter !== '') ? filter + '|' + keywords[i] : keywords[i];
        }
        //true (param 2) turns regex on, false (param 3) turns smart search off
        Table.search(filter, true, false).draw();
    }
});
4

I got this working by using regEx search. I used the following regEx to search throughout the table for keywords 10 99

^(?=.*?(10|99)).*?

Forked fiddle - http://jsfiddle.net/illuminatus/2j0Lz5or/6/

Ref: http://datatables.net/forums/discussion/12062/filtering-jquery-datatable-using-regular-expression

1
  • This approach is mostly suitable when you have a custom input field for the search (eg not the built in input) and a custom event for preprocessing before manually performing the search. OR-filtering can be implemented several ways, have added a more "streamlined" version to my answer below. Aug 20, 2014 at 12:29
3

The same but triggering search on "every" key press instead of pressing enter:

var dataTable = $('table').dataTable();
var input = $(".dataTables_filter input");
input.unbind('keyup search input').bind('keyup',
function(e) {
    if (input.val().length > 0) {
        var keywords = input.val().trim().split(' '), filter = '';
        for (var i = 0; i < keywords.length; i++) {
            filter = (filter !== '') ? filter + '|' + keywords[i] : keywords[i];
        }
        dataTable.fnFilter(filter, null, true, false, true, true);
        //                                ^ Treat as regular expression or not                        
    } else if (input.val().length == 0) {
        dataTable.fnFilter(" ", null, true, false, true, true);
    }
});
<script
  src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
  integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
  crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.6/css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/responsive/1.0.6/css/dataTables.responsive.css">
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/responsive/1.0.6/js/dataTables.responsive.js"></script>

<h5>OR SEARCH</h5>
<table>
  <thead>
    <tr>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
    </tr>
  </thead>
  <tbody>
      <tr><td>0</td><td>0</td><td>0</td><td>10</td></tr>
      <tr><td>0</td><td>5</td><td>0</td><td>0</td></tr>
      <tr><td>0</td><td>0</td><td>0</td><td>0</td></tr>
      <tr><td>2</td><td>0</td><td>0</td><td>10</td></tr>
      <tr><td>0</td><td>0</td><td>9</td><td>10</td></tr>
      <tr><td>0</td><td>0</td><td>99</td><td>0</td></tr>
  </tbody>
</table>

var dataTable = $('#your_datatable').dataTable();
var input = $(".dataTables_filter input");
input.unbind('keyup search input').bind('keyup',
function(e) {
    if (input.val().length > 0) {
        var keywords = input.val().trim().split(' '), filter = '';
        for (var i = 0; i < keywords.length; i++) {
            filter = (filter !== '') ? filter + '|' + keywords[i] : keywords[i];
        }
        dataTable.fnFilter(filter, null, true, false, true, true);
        //                                ^ Treat as regular expression or not                        
    } else if (input.val().length == 0) {
        dataTable.fnFilter(" ", null, true, false, true, true);
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.