searching/filtering using custom predicate function
searching/filtering using custom predicate function
Hi,
I would like to be able to "search" my datatable (that is, filter the displayed rows) by a custom predicate function that I define, which would serve as an additional "and" condition that must be met for a row to be displayed. Basically, I want to do:
$(t).DataTable({
customSearch: function(dataIndex) {
return dataIndex % 2 == 0; // whatever custom filter logic I want here
}
});
I was able to find plenty of documentation on searching using strings, regex's etc, but I did not see any support for doing this, so I made a 5-line change to datatables.js to support this feature.
My questions are:
1. Is there already support for this?
2. If there is not already support for this, how can I turn my 5-line change into a plug-in (or get it merged into the base code)?
FWIW the changes are as follows. Take them please...
diff --git a/datatables.js.orig b/datatables.js
index 80ec166..2ccfc32 100644
--- a/datatables.js.orig
+++ b/datatables.js
@@ -1024,6 +1024,7 @@
"sAjaxDataProp",
"iStateDuration",
"sDom",
+ "customSearch", // added
"bSortCellsTop",
"iTabIndex",
"fnStateLoadCallback",
@@ -4315,6 +4316,13 @@
/* Tell the draw function we have been filtering */
oSettings.bFiltered = true;
+
+
+ if(oSettings.customSearch) /// added
+ oSettings.aiDisplay = oSettings.aiDisplay.filter((ind) => { /// added
+ return oSettings.customSearch.call(oSettings.oInstance, ind); /// added
+ }); /// added
+
_fnCallbackFire( oSettings, null, 'search', [oSettings] );
}
This question has an accepted answers - jump to answer
Answers
Sounds like you want to create a search plugin:
https://datatables.net/manual/plug-ins/search
Kevin
Yes, that's perfect. Thank you!
Just one follow-up to generalize the search plug-in approach: if I want to use a different custom search function (or no function) for each datatable, where the table-specific function is determined at the time of the DataTable creation/initialization (e.g. because it uses local variables), what is the easiest approach? I suppose I could do:
plug-in:
and then when the datatable is created, do:
but is there a better way? In particular, is there a recommended place to store arbitrary, user-managed data (including a function), which would fill the role that I am using t._myCustomFunc to fill above?