0

I have a datatable and the 5th column of this table contains several labels. I also have a separate labels list with checkboxes, where user can select multiple labels and filter the table. I found the following way to filter the table:

table.column(5).search('value1|value2', true, false).draw();

This returns all the rows, that contain value1 OR value2, but I need to return the rows that contain both, value1 AND value2, but I could not find anything about this. I tried something like this as an experiment, but it did not work:

table.column(5).search('value1&value2', true, false).draw();

How do I search the datatable with an AND condition?

Vaxo Basilidze
  • 1,017
  • 13
  • 31
  • Try `(?=.*value1)(?=.*value2)(?=.*value3)` - and see [Regular Expressions: Is there an AND operator?](https://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator) - and similar questions. As long as there are no labels which are substrings of other labels, then I think that should work OK. Otherwise, you will need something more sophisticated. – andrewJames Jun 14 '22 at 19:21
  • A completely different approach would be to use the DataTables [search plug-in](https://datatables.net/manual/plug-ins/search). With that, you can write custom search code which would be more flexible than a pure regex approach. – andrewJames Jun 14 '22 at 19:29
  • @andrewJames Thanks for the idea. I did what you suggested and it worked. Added my solution as an answer for those, who encounters the similar issue – Vaxo Basilidze Jun 15 '22 at 08:05

1 Answers1

1

As andrewJames suggested in the comment, I used the Datatables search plug-in and created a custom filter function:

$('.labels-filter-button').unbind().click(function(){
    $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
        let selectedLabels = $('#labelsFilterSelector').val();
        let content = data[5];
        let rowIncludes = true;
        for (var i = 0; i < selectedLabels.length; i++) {
            if (content.indexOf(selectedLabels[i]) == -1){
                rowIncludes = false;
            }
        }
        return rowIncludes;
    });
    table.draw();
    $.fn.dataTable.ext.search.pop();
});

Works like a charm on any number of inputs.

Vaxo Basilidze
  • 1,017
  • 13
  • 31