【问题标题】:Datatables- Getting the total when there are null values数据表-当有空值时获取总数
【发布时间】:2019-06-04 21:05:48
【问题描述】:

我正在使用 DataTables 来计算列中的所有行并在表的页脚中显示总计。

问题出在这里:似乎每当我正在计算的列的任何行中有空值时,总数都会显示为 NaN。

我怎样才能让 DataTables 忽略列中的空值而只对非空值求和?

<div align="center">
     <table id = 'mytabl' class="display compact nowrap">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
    {% for num in numberdata.mytable_set.all %}
        <tr>
            <td>{{ num.col1 }}</td>
            <td>{{ num.col2 }}</td>
        </tr>
    {% endfor %}
    </tbody>
         <tfoot>
                <tr>
                    <th></th>
                    <th></th>
                </tr>
         </tfoot>
    </table>
            <script>
            $(document).ready(function() {
              $('#mytabl').DataTable({
                "searching": true,
                "pageLength": 40,
                "scrollX": true,
                "paging": false,
                "info": false,
                drawCallback: () => {
                  const table = $('#mytabl').DataTable();
                  const tableData = table.rows({
                    search: 'applied'
                  }).data().toArray();
                  const totals = tableData.reduce((total, rowData) => {
                    total[0] += parseFloat(rowData[1]);
                    total[1] += parseFloat(rowData[2]);
                    return total;
                  }, [0, 0]);
                  $(table.column(1).footer()).text(totals[0]);
                  $(table.column(2).footer()).text(totals[1]);
                }
              })
            });
            </script>

【问题讨论】:

  • 尝试将rowData[1]改为+rowData[1]......
  • 这可能是最好/最简单的方法^

标签: javascript jquery datatables


【解决方案1】:
const totals = tableData.reduce((total, rowData) => {
                total[0] += rowData[1] ? parseFloat(rowData[1]) : 0;
                total[1] += rowData[2] ? parseFloat(rowData[2]) : 0;
                return total;
              }

如果值为空加零怎么办

【讨论】:

  • 效果很好。如果列中的所有行都为空,有没有办法隐藏总计不显示?
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
相关资源
最近更新 更多