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.
Searching on individual columns can be performed using the columns().search() and column().search() methods. DataTables has a built in search algorithm referred to as "smart" searching and is designed to make searching the table data, easy to use for the end user.
With the current version of DataTables you can do this using the 'search' function. var data_table = $('#data-table'). DataTable(); var column_index = 0; data_table. columns(column_index).search('^(?:(?!-).)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With