datatables date filter

时光毁灭记忆、已成空白 提交于 2019-12-01 18:16:31

I think the example that's shown in the filter API page will do the trick:

$(document).ready(function() {
    var oTable = $('#example').dataTable();

    /* Add event listeners to the two range filtering inputs */
    $('#min').keyup( function() { oTable.fnDraw(); } );
    $('#max').keyup( function() { oTable.fnDraw(); } );
} );

What the range filtering extension you've included up above is looking for is a set of input boxes (probably datepicker style textboxes would work best). You should give them the ID's, by what I see in your code, dateStart and dateend. Then you can bind function() { oTable.fnDraw(); } to some event on either of those boxes ( like in the code above, they're bound to the keyup event) or it could be a filter button or whatever.

But now, each time that the table is drawn (using fnDraw()) it will take into account those dates and filter your zero-based iStartDateCol and iEndDateCol columns based on that range.

UPDATE: a more direct answer - just include the following in your document.ready function:

$('#dateStart').keyup( function() { oTable.fnDraw(); } );
$('#dateend').keyup( function() { oTable.fnDraw(); } );

If you want to filter a DataTable based on a date-range, you can try this function :

https://github.com/hemantrai88/datatables-date_range_filter

It is really simple to customize this function to make it work for different date-formats.

I found a solution without using any plugin (I used this also to filter table by a keyword)

function filterTableByDateRange(table) {

    var id = table.attr("id");
// I added class dt to a date-column of table 
    var dates = ($('#' + id + ' td.dt').map(function () {
        return new Date($(this).text());
    }).get());

//Here we init min and max date to be filtered with, if start date or end date is unset we set it to min and max existing dates of our table respectively
    var minSearchDate = $('#date_search_from').val()
        ? new Date($('#date_search_from').val())
        : new Date(Math.min.apply(null, dates));

    var maxSearchDate = $('#date_search_to').val()
        ? new Date($('#date_search_to').val())
        : new Date(Math.max.apply(null, dates));

    var allRows = $("#" + id + " tbody").find("tr");
    if (this.value == "") {
        allRows.show();
        return;
    }

    allRows.hide();

    allRows.filter(function (i, v) {
        var currDate = new Date($(this).find(".dt").html());
        if (currDate.setHours(0, 0, 0, 0) >= minSearchDate.setHours(0, 0, 0, 0) &&
            currDate.setHours(0, 0, 0, 0) <= maxSearchDate.setHours(0, 0, 0, 0)) {
            return true;
        }
        return false;
    }).show();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!