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('');
  });
 }
});

3 comments:

  1. Anonymous3:32 pm

    is it possible explain how do that for column filter

    thank you for sharing solutions

    ReplyDelete
  2. Anonymous1:53 am

    i found a solution for reset column filter with your code

    replace fnFilter(''); with fnFilterClear();

    one line extra

    $('#example thead input').val('');

    example because i change table to exaple
    thead because i prefer a tfoot


    thank you i hope this help (sorry my english)

    ReplyDelete
  3. Anonymous8:53 am

    i forget to say and this

    https://cdn.datatables.net/plug-ins/1.10.9/api/fnFilterClear.js">

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!