0

I'm trying to add a simple dropdown ("30 days", "60 days", "90 days", "1 year", "All dates") to a DataTables table that will filter the table by the value in the Date column.

I have looked at this answer and understand how to filter by a min and max range entered into text boxes, but can't figure out how to port that to a nice dropdown filter.

1
  • Could you perhaps provide a JSFiddle with some example data so we can experiment? Commented Jan 17, 2017 at 18:42

1 Answer 1

1

This should do what you require but will need some configuration:

$.fn.dataTableExt.afnFiltering.push(
  function(oSettings, aData, iDataIndex) {
    if (typeof $('#duration').val() !== "undefined") {
      var duration = $('#duration').val();
      var durationBits = duration.split(" ");
      var durationInt = ~~durationBits[0];
      var durationString = durationBits[1];
      var now = moment("2013/08/11", "YYYY/MM/DD");
      var targetDate = now.subtract(durationInt, durationString);
      var iDateCol = 4;
      var colDate = aData[iDateCol];
      if (duration === "All") {
        return true;
      } else {
        return moment(colDate, "YYYY/MM/DD").isSameOrAfter(targetDate);
      }
    } else {
      return true;
    }
  }
);

You'll also need momentjs to be available. I've got a contrived working example here. We basically take a date and use moment to test whether the date in the column is the same or after the date now with the relevant subtraction having been carried out. We then redraw the table when the select value changes. Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.