user2792945 user2792945 - 17 days ago 23
Ajax Question

Datatables get row data and then do fn.dataTable.ext.search.push

My alert is working but I don't know how to use the rowData to filter my other datatables instances.
Here's my codepen: http://codepen.io/smuglovsky/pen/YpNjXm?editors=1010

I learned how to "click on each row and get the data" here: https://datatables.net/release-datatables/examples/advanced_init/events_live.html

I also found how to "get the data from a row that was clicked upon" here: https://datatables.net/reference/type/row-selector

I know I'm almost there, but I'm stuck on line 460 of my codepen:

$('#example-sections tbody').on('click', 'tr', function() {
var data = table_sections.row(this).data();
var rowData = table_sections.row(this).data();
// ... do something with rowData
alert('You clicked on ' + data[0] + '\'s row');
$.fn.dataTable.ext.search.push(
function(settings, data, rows, dataIndex, rowIndex, rowData) {
// I want to filter the rowData, just like the alert is doing
return data[0] == +data[0] ? true : false;
}
);
table_main.draw();
table_books.draw();
$.fn.dataTable.ext.search.pop();
});

Answer

So using "$.fn.dataTable.ext.search" adds a search custom function to ALL data table instances. What I think you want here is to filter other DataTable instances using the value from a particular grid row click. If so you would want to approach this problem a little differently.

The following solution assumes that the first column of your "example-sections" grid corresponds to the column you want to search on your "table_main" and "table_books" columns. If so you can merely get the column for "table_main" and "table_books" using the index and apply the search to it using the data from row you clicked on.

$('#example-sections tbody').on('click', 'tr', function() {
  var rowData = table_sections.row(this).data();
  // ... do something with rowData
  alert('You clicked on ' + rowData[0] + '\'s row');

  // Lets build a regular expression that will give only exact matches.
  var searchRegExp = new RegExp("^" + rowData[0] + "$");

  // Ok so we are going to use a regex.  Second param is to turn on
  // search by a regular expression.  The third param is to turn off "smart"
  // searching which would conflict.  The last param is to turn off case 
  // insensitive matching.
  table_main.column(0).search(searchRegExp, true, false, false).draw();
  table_books.column(0).search(searchRegExp, true, false, false).draw();
});

NOTE: For "table_main.column(0)" the "0" is the index of the column in the data set so if you have hidden columns those count towards this index. For example lets say my first visible column is an "ID" column but I have TWO hidden columns that are defined within my "columns" definition before the "ID" column then the index of the "ID" column would be "2" not "0".

EDIT: changed search to only return exact match. Reference: https://datatables.net/reference/api/search()