数据表过滤日期范围,不使用任何数据表插件

时间:2018-01-09 09:00:41

标签: jquery datatable datepicker datatables date-range

以下是我的html结构

<div class="filters">
    <input type="text" name="hireDate" id="hireDate">
    <input type="text" name="terminationDate" id="terminationDate">
</div>

<table id="exampleTable">
    <thead>
    <tr>
        <th>Employee Name</th>
        <th>Hire Date</th>
        <th>Termination Date</th>
        <th>Designation </th>
        <th> Hire Date epoch </th>
        <th> Termination Date epoch </th>
    </tr>
    </thead>
    <tbody>
        <!-- table data here -->
    </tbody>
</table>

我想基于hireDate和terminationDate选择过滤表数据

  1. 如果用户选择HireDateterminationDate1-jan-2016, 分别为31-jan-2016,然后表应显示所有行 有HireDate >= 1-jan-2016TerminationDate <= 31-jan-2016
  2. 如果用户仅选择HireDate,则表格应仅显示行 它有HireDate >= userSelectedHireDate
  3. 如果用户仅选择TerminationDate,则表格应仅显示 具有TerminationDate <= userSelectedTerminationDate
  4. 的行

1 个答案:

答案 0 :(得分:0)

以下是我解决此问题的方法

var dataTable = $('#exampleTable').DataTable({
    "columnDefs" : [{
                "targets":[4, 5],
                "visible":false,
            }],
 });

$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var startDate = $('#hireDate').val();
        //convert date into epoch
        startDate = (startDate == '') ? -1 : moment(startDate, 'MMMM DD, YYYY').valueOf()/1000;

        var endDate = $('#terminationDate').val();
        endDate = (endDate == '') ? -1 : moment(endDate, 'MMMM DD, YYYY').valueOf()/1000;

        var tableStartDate = (data[4] == '--') ? 0 : data[4];
        var tableEndDate = (data[5] == '--') ? 1 : data[5];

        //Show all rows if start and end date is not selected
        if(startDate == -1 && endDate == -1) {
            return true;
        }

        if(tableStartDate >= startDate) {
            if(endDate == -1) {
                return true;
            }

            if(tableEndDate != 1 && tableEndDate <= endDate){
                return true;
            }
            return false;
        }
        return false;
    }
);


$('#hireDate').on('change', function(){
    $('#exampleTable').dataTable().api().column(1).search('', true, false).draw();
});

$('#terminationDate').on('change', function(){
    $('#exampleTable').dataTable().api().column(2).search('', true, false).draw();
});