JQUery.DataTables custom filter

2019-08-29 10:09发布

问题:

In my ASP.NET MVC application I use jQuery DataTables in order to list my clients. My jQuery version is 3.3.1. I use this code for my DataTable and it works fine:

The objectif is to filter the datatable by another search input (Design of the application is imposed by the designer). To achieve this, I use this code

 <input type="text" onkeyup="filterTable(this);" id="txt-search" maxlength="20" placeholder="Rechercher..." class="capron-input-text pull-right" />   


//Sets the value of the search input of the datatable and triggers the keyup event. It works fine.
function filterTable(sender) {
    var filterText = $(sender).val();
    var searchInput = $("#tbl-data_filter").find("input");
    $(searchInput).val(filterText);

    $(searchInput).trigger("keyup");
}

 $(document).ready(function() {
  $('#tbl-data').dataTable();

  // These two lines hides related fields. It works.
  $("#tbl-data_filter").hide();
  $("#tbl-data_length").hide();
});

When I translate the DataTable using this code, the localisation works fine but the search input and the row count Dropdown stays visible:

 $(document).ready(function () {
  $('#tbl-data').dataTable({
    "language": {
      "url": "/Resources/Localisation/French.json"
    }
  });

  // It doesn't work.
  $("#tbl-data_filter").hide();
  $("#tbl-data_length").hide();
});

If I call these lines in a manual event, like the click event of any control, it works again. I think the DataTable() method is asynchronous and before it completes the translation and creation of elements that I want to hide, the lines execute.

Does anyone have any ideas?

回答1:

After some search, I found this solution:

I added these lines in my css

#tbl-data_filter{
   display:none;
}

#tbl-data_length{
  display:none;
}