cortex
cortex

Reputation: 81

Datatables - search by string, not substring

I've been trying to make search in datatables to search for full string, not substring of that string.

I have usernames: Ivan Test and Test Usiver If I search for "iv" or "Iv" result I would expect is only "Ivan Test", but I get both users, as second user contains inside of his string "Test UsIVer"

enter image description here

I've tried with this: $('#TablicaRacuni').DataTable().search($(this).val(), false, false, false); and this $('#TablicaRacuni').DataTable().search("^" + $(this).val() + "$", true, false, true).draw(); With second function there is bug as ^ and $ shows up on search input box like this:

enter image description here

All random combinations of true and false and can't get this to work exactly how I want.

Stock function to print table: $('#TablicaRacuni').DataTable();

It doesn't have to be specific column search, I want all columns to be searchable for example If i input "d" I would expect all diesel bills and all users with "d" for first letter.

Upvotes: 0

Views: 1082

Answers (1)

andrewJames
andrewJames

Reputation: 22022

You can use the search plug-in to intercept search (filter) events, and then apply your own filtering logic. The plug-in is already available - you do not need to add it.

Here is an example for "begins with", also assuming that the search is case insensitive:

$(document).ready(function() {

  $('#example').DataTable( {
    // your normal initialization options here
    // no need for any special search options
  } );
  
  $.fn.dataTable.ext.search.push(
    function( settings, searchData, index, rowData, counter ) {
      var match = false;
      var searchTerm = settings.oPreviousSearch.sSearch.toLowerCase();
      searchData.forEach(function (item, index) {
        if (item.toLowerCase().startsWith(searchTerm)) {
          match = true;
       }
      } );
      return match;
    }
  );

} );

The search term is assumed to be entered into the standard global search field, provided by DataTables out-of-the-box. We get the user-entered search term from settings.

Each searchData represents one row of data, as an array of values - so we iterate over each value looking for a match.

(If you wanted to change this to "exact match", you would alter the if condition accordingly. The only downside here is that the user experience might be a bit surprising. Each keystroke causes a re-filtering of the data. So, you may find every row disappears, until you have typed in an exact match for a field. In this case, a search "submit" button might give a better user experience.)

Upvotes: 1

Related Questions