user3788671
user3788671

Reputation: 2057

Customizing the jquery.datatables plugin to filter with a regex on two columns

I am using the jquery datatables plugin found here. There are two columns named "New GL" and "Old GL". The datatables plugin has a built in feature called search which filters the data in the table based on the keyword you enter into the textbox.

Here is what my data currently looks like: enter image description here

When I type "40.88.1010.0" or "40.88.600000.05" into the textbox I want this record to appear. enter image description here

The same rule applies to all of the records. I want the search to continue to filter all of columns using one single textbox but for the columns "New GL" and "Old GL"...I want the user to be able to use both "-" and "." characters.

My initial thought would be if the datatables had a regex option it would work because "." in regex is any character. But I only want the rule to apply to those two columns.

Is this possible to do using the datatables plugin?

Here is my current datatable initialization code:

$(document).ready(function () {
    var table = $('#datatable').DataTable({ "iDisplayLength": 50 });
});

Upvotes: 2

Views: 557

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58890

SOLUTION

You need to implement custom search function as shown below.

The drawback of this method is that content in other columns will also be searched in the same manner, i.e. searched by using either . or - characters.

$(document).ready(function () {
    var table = $('#datatable').DataTable({ 
       "pageLength": 50 
    });

    $('.dataTables_filter input', table.table().container())
        .off('.DT')
        .on('keyup.DT cut.DT paste.DT input.DT search.DT', function (e) {
            // If the length is 3 or more characters, or the user pressed ENTER, search
            if(this.value.length > 0){            
                // Escape the expression so we can perform a regex match
                var val = $.fn.dataTable.util.escapeRegex(this.value);

                // Add regular expression to match both . and - characters
                val = val.replace(/(\\\-|\\\.)/g, "[\\\.\\\-]");

                // Call the API search function
                table.search(val, true, false).draw();

            } else {
                // Ensure we clear the search if they backspace far enough
                table.search("").draw();
            }    
        });
});

DEMO

See this jsFiddle for code and demonstration.

Upvotes: 1

dpnevmatikos
dpnevmatikos

Reputation: 79

You can add the data-search attribute found here. Your rows then would become something like that:

<tr>
  <td data-search="40.88.1010.0">40-88-1010-0</td>
  <td data-search="40.88.600000.05">40-88600000-05</td>
</tr>

Datatables' filtering by default uses data from all rows.

Upvotes: 1

Related Questions