Using functions in multiple DataTables

Using functions in multiple DataTables

tabledoctabledoc Posts: 2Questions: 1Answers: 0

This may be more a basic JavaScript question, but I have a page with multiple DataTables that all use similar columnDefs, footerCalbacks, etc.

Is there a way to define the columnDefs, footerCallbacks, etc. once and reuse them in multiple DataTables? I find myself copy and pasting large segments of code.

For instance, one of my footerCallbacks to sum the column values looks like this and I have it copied into every DataTable breaking DRY principle.


      footerCallback: function (row, data, start, end, display) {
        var api = this.api(),

        // Remove the formatting to get integer data for summation
        const intVal = function (i) {
          return typeof i === 'string'
            ? i.replace(/[\$a-zA-Z, ]/g, '') * 1
            : typeof i === 'number'
            ? i
            : 0;

        const cols = new Int8Array(
          document.getElementById('table_locations').rows[0].cells.length - 1
        ).map((curr, index) => (curr = index + 1));

        for (let index = 0; index < cols.length; index++) {
          const col_data = cols[index];
          // Total over all pages
          const total = api
            .reduce(function (a, b) {
              return intVal(a) + intVal(b);
            }, 0);

          // Total over this page
          const pageTotal = api
            .column(col_data, {
              page: 'current',
            .reduce(function (a, b) {
              return intVal(a) + intVal(b);
            }, 0);

          // Update footer

This question has accepted answers - jump to:


  • colincolin Posts: 14,800Questions: 1Answers: 2,524
    Answer ✓

    Yep, that's more standard JS. You can make those callback functions, something like this. Likewise, you can make objects for the columns and other declarations that you just reuse.


  • kthorngrenkthorngren Posts: 18,539Questions: 25Answers: 4,396
    Answer ✓

    Also checkout the docs for creating default options.


  • tabledoctabledoc Posts: 2Questions: 1Answers: 0

    Thanks! This was exactly what I was looking for. Still learning JS, but loving DataTables!

Sign In or Register to comment.