DEV Community

William Kwadwo Owusu
William Kwadwo Owusu

Posted on

Filtering a table by date

Image description

Assuming you have table in your project and would like to filter the values by date. This simple code will enable you to filter it using from-to dates.

<div class="row">
  <div class="col-md-3">
    <h4>Date from</h4>
    <input type="date" class="form-control" id="datefilterfrom" data-date-split-input="true">
  </div>
  <div class="col-md-3">
    <h4>Date to</h4>
    <input type="date" class="form-control" id="datefilterto" data-date-split-input="true">
  </div>
</div>
<table id="myTable" class="table" border="1">
  <tr>
    <td>nothing</td>
    <td>nothing</td>
    <td>18/07/2018</td>
    <td>nothing</td>
  </tr>
  <tr>
    <td>nothing</td>
    <td>nothing</td>
    <td>19/07/2018</td>
    <td>nothing</td>
  </tr>
  <tr>
    <td>nothing</td>
    <td>nothing</td>
    <td>20/07/2018</td>
    <td>nothing</td>
  </tr>
</table>

Enter fullscreen mode Exit fullscreen mode

The javascript code to actually filter the table and redraw the table:

function filterRows() {
  var from = $('#datefilterfrom').val();
  var to = $('#datefilterto').val();

  if (!from && !to) { // no value for from and to
    return;
  }

  from = from || '1970-01-01'; // default from to a old date if it is not set
  to = to || '2999-12-31';

  var dateFrom = moment(from);
  var dateTo = moment(to);

  $('#myTable tr').each(function(i, tr) {
    var val = $(tr).find("td:nth-child(3)").text();
    var dateVal = moment(val, "DD/MM/YYYY");
    var visible = (dateVal.isBetween(dateFrom, dateTo, null, [])) ? "" : "none"; // [] for inclusive
    $(tr).css('display', visible);
  });
}

$('#datefilterfrom').on("change", filterRows);
$('#datefilterto').on("change", filterRows);

Enter fullscreen mode Exit fullscreen mode

Give me a follow if you found this helpful! :-)

Top comments (0)