使DataTables总计行不受排序/过滤的影响

时间:2019-03-22 21:30:30

标签: javascript jquery datatables

我正在使用jquery数据表。我还在最后tr中添加了总计。当我按日期范围或数据表默认搜索条件搜索任何数据时,我的总计未显示。如何解决搜索结果总计问题?

这是我的剧本

$.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                    var min = $('#datepicker_from').datepicker("getDate");
                    var max = $('#datepicker_to').datepicker("getDate");
                    var startDate = new Date(data[1]);
                    if (min == null && max == null) {
                        return true;
                    }
                    if (min == null && startDate <= max) {
                        return true;
                    }
                    if (max == null && startDate >= min) {
                        return true;
                    }
                    if (startDate <= max && startDate >= min) {
                        return true;
                    }
                    return false;
                }
            );


            $("#datepicker_from").datepicker({
                onSelect: function () {
                    table.draw();
                },
                changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true

            });
            $("#datepicker_to").datepicker({
                onSelect: function () {
                    table.draw();
                }, changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true

            });
            var table = $('#datatable').DataTable();

            // Event listener to the two range filtering inputs to redraw on input
            $('#datepicker_from, #datepicker_to').change(function () {
                table.draw();
            });

1 个答案:

答案 0 :(得分:1)

考虑到,您没有共享某些先决条件,我让我自己弥补自己的例子。

因此,正如您所说的那样,您的问题的最佳解决方案是将总计放入<tfoot>行,这样它们就不会受到过滤或排序的影响:

//source data
const srcData = [
  {item: 'apple', order: '12/03/2019', cost: 15},
  {item: 'pear', order: '24/10/2018', cost: 24},
  {item: 'banana', order: '13/02/2019', cost: 14},
  {item: 'plum', order: '11/12/2018', cost: 26}
];
//DataTable initialization
const dataTable = $('#mytable').DataTable({
  dom: 't',
  data: srcData,
  columns: [
    {title: 'Item', data: 'item'},
    {title: 'Order date', data: 'order'},
    {title: 'Cost', data: 'cost'}
  ],
  drawCallback: () => {
	//append tfoot and populate it with total cost
	$('#mytable tfoot').remove();
	$('#mytable').append(`<tfoot><td colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td></tfoot>`);
  }
});
//custom date range filter
$.fn.DataTable.ext.search.push((settings, row) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') && 
	(new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == ''));
//bind 'from' / 'to' inputs
$('input[type="date"]').on('change', function(){
  if($(this).attr('id') == 'startdate') $('#enddate').attr('min', $(this).val());
  else if ($(this).attr('id') == 'enddate') $('#startdate').attr('max', $(this).val());
  dataTable.draw();
});
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <label>from:</label>
  <input type="date" id="startdate"></input>
  <label>to:</label>
  <input type="date" id="enddate"></input>
  <table id="mytable"></table>
</body>
</html>

但是,如果由于某种原因,您希望将总计作为常规行保留在<tbody>的底部,则可以更改drawCallback以在每次重绘时追加总计行以确保总计行持久性,或将id属性附加到其上,并通过自定义过滤器传递总计行。

如果首选使用前者,则可以将drawCallback选项更改为(回到我的示例):

  drawCallback: () => {
    //append row to tbody and populate it with total cost
    $('#mytable #totals').remove();
    $('#mytable tbody').append(`<td id="totals" colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td>`);
  }

如果后一种选择更适合您,并且您使用id="totals"构造总计行,则过滤器(再次回到我的示例)将看起来像(请注意最后一行):

//custom date range filter
$.fn.DataTable.ext.search.push((settings, row, index) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') && 
    (new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == '')) 
    || $(dataTable.row(index).node()).is('#totals');