Correct way to redraw a DataTable? Getting errors: "no method 'fnDraw'" and "cannot read property 'oFeatures'"

datatables, jquery

Solution

In your modified code, you're calling `fnDraw()` on the jQuery `$('table')` object — which has no associated `fnDraw()` method — instead of the DataTable object.

You'll want to call `fnDraw()` on the object you originally call `dataTable()` on, as in:

$(document).ready(function() {
  var oTable = $('#yourDataTable').dataTable();
  oTable.fnDraw();
});

So this wouldn't work:

$(document).ready(function() {
  var oTable = $('#yourDataTable');
  oTable.fnDraw(); // Won't work, because the dataTable() method wasn't called above
});

If you can't access the original object you called `dataTable()` on any more for some reason (difficult to say without seeing more of your code), you could try reinitializing the table by calling `dataTable()` on `table` and optionally passing in `bDestroy` or `bRetrieve`, depending on what you need. So something like:

table.dataTable({ "bRetrieve": true });

(I'm honestly not sure whether you'd need to call `fnDraw()` any more after that.)

Problem

I have inherited the following code: ``` // Show / Hide table rows from checkboxes $("table.data#report-table .warning").toggle($("#warning_checkbox").is(":checked")); $("#warning_checkbox").click(function() { $("table.data#report-table .warning").toggle($("#warning_checkbox").is(":checked")); $('.data_table#report-table').dataTable().fnDraw(); }); ``` When a checkbox with id `warning_checkbox` is checked, it shows/hides the rows (actually, `tbody` elements) of `table.data#report-table` which have the class `.warning` As far as i can see, there is no `'.data_table#report-table` element on the page - so i assumed something wouldnt work. However - it (magically?) does, i.e. the table is redrawn as expected, preserving its correct settings. I do however get the following error in the Chrome console: ``` Uncaught TypeError: Cannot read property 'oFeatures' of null ``` Which i thought may be due to the missing element (but then how does it still work?) Anyway, i rewrote the code as a function as i need to reuse it elsewhere: ``` var checkbox_rows = function(checkbox_id, table_id, tbody_class) { var checkbox = $('div.buttons input[id$='+checkbox_id+']'); var table = $('table.data[id$='+table_id+']'); checkbox.click(function() { $('tbody[class$='+tbody_class+']', table).toggle(checkbox.is(':checked')); table.fnDraw(); }); } checkbox_rows('warning_checkbox', 'report-table', 'warning'); ``` This also works (and makes more sense to me) - but now i get a different error in the Chrome Console: ``` Uncaught TypeError: Object [object Object] has no method 'fnDraw' ``` So my question is, what am i doing wrong? What is the correct way to redraw a DataTable? Thank you

Original source