Forem

William Kwadwo Owusu
William Kwadwo Owusu

Posted on

2 1

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! :-)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay