Search code examples
javascriptjquerydatatablesdatepickerdatatables-1.10

Add datepicker to filter data in Datatable


I would like to add a datepicker to filter data in a Datatable. I saw many example where the datepicker is used with a range of dates, but I would like that the Datatable shows only the data which contain the date selected in the datepicker.

I've tried to do it here: https://jsfiddle.net/c9q5b0k3/3/

The javascript code I've wrote is:

$(document).ready(function() {
  $('.datepicker').datepicker({
    format: "yyyy/mm/dd"
  });

});


$.fn.dataTable.ext.search.push(
  function(settings, data, dataIndex) {
    var dateSelected = $('#date').val();
    var date = data[4];
    if (dateSelected === "") {
      return true;
    }
    if (date === dateSelected) {
      return true;
    }
    return false;
  }
);

$(document).ready(function() {
  var table = $('#sspTable').DataTable({
    responsive: true
  });
  $('#date').keyup(function() {
    table.draw();
  });
    });

But the problem that it only works if I select a date in the datepicker and then I click the arrows in the Datatables(the ones that order the data) or if I press multiple times Enter.

What is the problem? Is it possible otherwise to add the datepicker to the search bar of the Datatable?

Thanks in advance!


Solution

  • You need to call table.draw() when a value is selected in the datepicker. To do that you can amend the existing keyup event handler you have to also include change, like this:

    $('#date').on('keyup change', function() {
      table.draw();
    });
    

    Updated fiddle