Summing Values in a Column

This example is summing the values of a column, giving totals for both all rows and just the selected rows. It is also possible using the DataTables API to show records just on the displayed page, or the results of a filter - see selector-modifier.

This example was achieved by adding the following code into the document:

document.addEventListener('ct-ready', function (e) {
  var table = e.table;
  var editor = e.editor;
  var total;

  var intVal = function(i) {
    return typeof i === 'undefined' ? 0 : i * 1;
  };

  var span = function(col, val) {
    return '<span class="ct-content__link ct-content__pill" style="background: ' + col + '; color: #000000">' + $.fn.dataTable.render.number().display(val) + '</span>';
  }
  
  table.on('draw.dt select.dt deselect.dt', function() {
    let selected = 0;
    let total = 0;
    table.rows().every(function() {
      let val = intVal(this.data()['dp-11']);

      total += val;

      if (this.selected()) {
        selected += val;
      }
    })

    $('.summary').html('Total ' + span('#d1cfe7', total) + '<br> Selected ' + span('#f9d7e7', selected));
  });
});

Other examples