25 Aug 2014

Adding a Clear Filter / Clear Search Button to DataTables

I wanted a generic way to add a "clear filter" button to the text filter on all the DataTables on a site.

One way would be to change the input type of the filter to "search" - then HTML5 browsers will automatically show a clear widget. However, you'd have to press return after clicking it, so I wanted a one-click solution.

Here's what I came up with. It works with DataTables 1.9.


// Setup DataTable Defaults
$.extend( $.fn.dataTable.defaults, {
 fnInitComplete: function(oSettings, json) {

  // Add "Clear Filter" button to Filter
  var btnClear = $('<button class="btnClearDataTableFilter">CLEAR</button>');
  btnClear.appendTo($('#' + oSettings.sTableId).parents('.dataTables_wrapper').find('.dataTables_filter'));
  $('#' + oSettings.sTableId + '_wrapper .btnClearDataTableFilter').click(function () {
   $('#' + oSettings.sTableId).dataTable().fnFilter('');
  });
 }
});
If I helped you out today, you can buy me a beer below. Cheers!