How to search multiple columns in DataTables?

I am trying to combine column search and regular search on specific columns.

If you look at this example , I want to be able to search for the Name and Position columns, with β€œnormal” searching and ignoring the rest, but I still want to be able to select a value at the bottom of the Office column.

I tried using this:

 columnDefs: [{ targets: [2], searchable: false }] 

But it also disables column search.
I also tried writing custom search across multiple columns:

 var search = 'Software'; $('#example').DataTable().column(0).search(search).draw(); $('#example').DataTable().column(1).search(search).draw(); 

But this only shows the rows in which the BOTH columns contain the search value, and not 1 of them. (what is not happening).

I also tried columns().search() , but this gives the same result as the user search above.

How to enable a separate column search, but disconnect the same column from the general search?

+6
source share
1 answer

You can override the built-in search / filter using a custom filter :

 $('.dataTables_filter input').unbind().on('keyup', function() { var searchTerm = this.value.toLowerCase(); $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) { //search only in column 1 and 2 if (~data[0].toLowerCase().indexOf(searchTerm)) return true; if (~data[1].toLowerCase().indexOf(searchTerm)) return true; return false; }) table.draw(); $.fn.dataTable.ext.search.pop(); }) 

Thus, the "normal search" only applies to the first two columns, Name and Position - and you still have the selection fields in the footer. Forked fiddle β†’ https://jsfiddle.net/g9gLjtjh/

+10
source

All Articles