0

I'm using DataTables to calculate the all of the rows in the column and display the total in the footer of the table.

Here's the problem: It appears that whenever there is a null value in any of the rows of the column that I'm calculating, the total gets displayed as NaN.

How can I get DataTables to ignore the null values in the column and just total up the non-null values?

<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>
2
  • 1
    try changing from rowData[1] to +rowData[1]...... Commented Jun 4, 2019 at 21:08
  • 1
    This is probably the best/easiest way to do it ^ Commented Jun 4, 2019 at 21:31

1 Answer 1

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;
              }

How bout this if the value is null add zero

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

1 Comment

That works pretty well. And is there a way to hide the total from being displayed if all rows in the column are null?

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.