Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables clear input filters

I am using datatables v1.10.11 and Jquery v 2.2.0

I have one table with two input search filters;

<input type="text" id="myInputTextField1" class="form-control"> <!--search one-->

<input type="text" id="myInputTextField2" class="form-control"> <!--search two-->

My datatable JS;

$(document).ready(function() {
    $('#example').dataTable({});
}); 

$('#myInputTextField1').keyup(function(){
  table.search($(this).val()).draw() ;
})

$('#myInputTextField2').keyup(function(){
  table.search($(this).val()).draw() ;
})

The search is working fine, no issues.

How would I incorporate a simple button that when clicked, will clear both input fields and reset the table to it's default state? For example;

<button type="button" id="test">Clear Filters</button>

<table id="example">
<thead>
  <tr>
    <th>COLUMN 1</th>
    <th>COLUMN 2</th>
    <th>COLUMN 3</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>ROW 1</td>
    <td>ROW 1</td>
    <td>ROW 1</td>
  </tr>
  <tr>
    <td>ROW 2</td>
    <td>ROW 2</td>
    <td>ROW 2</td>
  </tr>
  <tr>
    <td>ROW 3</td>
    <td>ROW 3</td>
    <td>ROW 3</td>
  </tr>  
</tbody>
</table>

Any help is appreciated.

like image 955
jonboy Avatar asked Sep 18 '25 12:09

jonboy


1 Answers

To reset a search filter, just call search() again with an empty string. Similarly you can clear the value of an input by setting its value to an empty string. Try this:

$('#test').click(function() {
    $('#myInputTextField1, #myInputTextField2').val('');
    table.search('').draw(); //required after
});

Working example

like image 53
Rory McCrossan Avatar answered Sep 21 '25 04:09

Rory McCrossan