Datatables清除输入过滤器

4

我正在使用DataTables v1.10.11和jQuery v2.2.0。

我有一个表格,其中包含两个输入搜索过滤器;

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

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

我的Datatable JS;

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

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

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

搜索功能完好,没有问题。

我该如何添加一个简单的按钮,当点击时,清除两个输入框中的内容并将表格重置为默认状态?例如:

<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>

非常感谢您的帮助。

2个回答

7

要重置搜索过滤器,只需再次使用空字符串调用search()。同样,您可以通过将其值设置为空字符串来清除输入的值。试一下:

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

Working example


0
<button type="button" id="test" class="btn btn-primary">Clear Filters</button>

  $('#test').click(function () {
              $('input:text').val('');
              var datatableVariable = $('#tblBusinessDev').dataTable();
              datatableVariable.fnFilterClear();
              $('#tblBusinessDev tfoot input').val('').change();
          });


//filter code

jQuery.fn.dataTableExt.oApi.fnFilterClear = function (oSettings) {
              var i, iLen;

              /* Remove global filter */
              oSettings.oPreviousSearch.sSearch = "";

              /* Remove the text of the global filter in the input boxes */
              if (typeof oSettings.aanFeatures.f != 'undefined') {
                  var n = oSettings.aanFeatures.f;
                  for (i = 0, iLen = n.length ; i < iLen ; i++) {
                      $('input', n[i]).val('');
                  }
              }

              /* Remove the search text for the column filters - NOTE - if you have input boxes for these
               * filters, these will need to be reset
               */
              for (i = 0, iLen = oSettings.aoPreSearchCols.length ; i < iLen ; i++) {
                  oSettings.aoPreSearchCols[i].sSearch = "";
              }

              /* Redraw */
              oSettings.oApi._fnReDraw(oSettings);
          };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接