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 intVal = function(i) {
    return typeof i === 'undefined' ? 0 : i * 1;
  };

  // Initialise a DataTable for the counts
  var salaries = $('#salaries').DataTable({
    // Disable features
    searching: false,
    paging: false,
    info: false,
    columnDefs: [{
      // Render the currency field in the salaries table
      targets: [0,1],
      render: $.fn.dataTable.render.number(',', '.', 0, '$')
    }]
  });

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

	  salaries.rows().remove();
	  salaries.row.add([total, selected]);
	  salaries.columns.adjust().draw();
    })
  });
});

Other examples