sum column in select rows

Got something cool to share with AppGini users? Feel free to post it here!
Post Reply
User avatar
baudwalker
Veteran Member
Posts:191
Joined: 2015-02-03 08:08
Location: Bellingen NSW Australia

sum column in select rows

Post by baudwalker » 2026-04-02 02:29

Hi all,

while in table view, I would like to be able to select a number of rows and have the total sum of a column dynamically, possibly in a popup window.

thank you in anticipation, Barry

saymaad
AppGini Super Hero
AppGini Super Hero
Posts:131
Joined: 2024-06-03 16:17

Re: sum column in select rows

Post by saymaad » 2026-04-02 08:21

Hello Barry,

I have put together a custom script for you that does exactly what you are looking for. The script monitors the checkboxes in your table view. Whenever you select or deselect a row, it automatically finds the value in the Balance column (configurable) for those specific records. It then calculates the total sum and displays it in a neat, floating box at the bottom right of your screen or shows the button to view the total in a modal window depending on your preference.

Simple Configuration
At the top of the script, you will find a config section where you can easily customize how it behaves:
  1. fieldName: Set this to the name of the column you want to sum (like 'balance').
  2. decimalPlaces: Control how many numbers appear after the decimal point.
  3. outputMode: You can choose between 'floating' to see a live box at the bottom of the screen, or 'modal' to add a Show Summary (configurable) button to your toolbar that opens a popup window.
  4. showTotal/showAverage: Toggle these to true or false to choose which stats to display, (bonus if you want min / max /avg).
  5. numberFormats: The script is already set up to handle various global formats like 1,234.56 or 1.234,56 automatically.
How to use it
Just copy the code into your hooks/tablename-tv.js file. It is designed to be plug and play once you set your field name.

Code: Select all

$j(function() {

    /* ============================
       CONFIGURATION SECTION
       ============================ */

    const config = {
        fieldName: 'balance', // The name of the column to sum

        decimalPlaces: 2, // How many decimals to show in output

        outputMode: 'floating', // 'floating' or 'modal'

        buttonLabel: 'Show Summary',
        
        buttonIcon: 'glyphicon glyphicon-signal',

        // Enable/disable individual statistics
        showTotal: true,
        showAverage: false,
        showMin: false,
        showMax: false,

        numberFormats: [
            { thousand: ',', decimal: '.' },   // 1,234.56
            { thousand: '.', decimal: ',' },   // 1.234,56
            { thousand: ' ', decimal: ',' },   // 1 234,56
            { thousand: '', decimal: '.' }     // 1234.56
        ]
    };

    /* ============================
       INTERNAL FUNCTIONS
       ============================ */

    // Floating box (only used in floating mode)
    let box = $j('<div id="sumBox"></div>').css({
        position: 'fixed',
        bottom: '20px',
        right: '20px',
        padding: '12px 18px',
        background: '#333',
        color: '#fff',
        borderRadius: '6px',
        fontSize: '16px',
        display: 'none',
        zIndex: 9999
    }).appendTo('body');

    // Parse numbers in multiple formats
    function parseNumber(str) {
        str = str.trim();

        for (let fmt of config.numberFormats) {
            let regex = new RegExp('\\' + fmt.thousand, 'g');
            let cleaned = str.replace(regex, '').replace(fmt.decimal, '.');

            let val = parseFloat(cleaned);
            if (!isNaN(val)) return val;
        }

        return NaN;
    }

    // Calculate stats
    function calculateStats() {
        let values = [];

        $j('input.record_selector:checked').each(function() {
            let row = $j(this).closest('tr');
            let text = row.find('td.' + AppGini.currentTableName() + '-' + config.fieldName + ' a').text();

            let value = parseNumber(text);
            if (!isNaN(value)) values.push(value);
        });

        if (values.length === 0) return null;

        let stats = {};

        if (config.showTotal) stats.total = values.reduce((a, b) => a + b, 0);
        if (config.showAverage) stats.avg = values.reduce((a, b) => a + b, 0) / values.length;
        if (config.showMin) stats.min = Math.min(...values);
        if (config.showMax) stats.max = Math.max(...values);

        return stats;
    }

    // Format number
    function fmt(num) {
        return num.toLocaleString(undefined, {
            minimumFractionDigits: config.decimalPlaces,
            maximumFractionDigits: config.decimalPlaces
        });
    }

    // Build HTML summary
    function buildSummary(stats) {
        let html = `<div style="font-size: 16px; line-height: 1.6;">`;

        if (config.showTotal && stats.total !== undefined)
            html += `<b>Total:</b> ${fmt(stats.total)}<br>`;

        if (config.showAverage && stats.avg !== undefined)
            html += `<b>Average:</b> ${fmt(stats.avg)}<br>`;

        if (config.showMin && stats.min !== undefined)
            html += `<b>Minimum:</b> ${fmt(stats.min)}<br>`;

        if (config.showMax && stats.max !== undefined)
            html += `<b>Maximum:</b> ${fmt(stats.max)}<br>`;

        html += `</div>`;
        return html;
    }

    // Show result
    function showResult(stats) {
        if (!stats) {
            if (config.outputMode === 'floating') box.hide();
            return;
        }

        let html = buildSummary(stats);

        if (config.outputMode === 'modal') {
            modal_window({
                title: 'Selected Rows Summary',
                message: html,
                footer: ''
            });
        } else {
            box.html(html).show();
        }
    }

    function updateFloating() {
        if (config.outputMode !== 'floating') return;
        let stats = calculateStats();
        if (!stats) box.hide();
        else showResult(stats);
    }

    /* ============================
       BUTTON INTEGRATION
       ============================ */

    function addToolbarButton() {
        if (config.outputMode !== 'modal') return;

        let btn = `
            <button type="button" id="sumSelectedBtn" class="btn btn-default">
                <i class="${config.buttonIcon}"></i> ${config.buttonLabel}
            </button>
        `;

        $j('#top_buttons .all_records').append(btn);

        $j('#sumSelectedBtn').on('click', function() {
            let stats = calculateStats();
            showResult(stats);
        });
    }

    addToolbarButton();

    /* ============================
       EVENT BINDINGS
       ============================ */

    // Floating mode updates live
    $j(document).on('change', 'input.record_selector', updateFloating);

    AppGini.tableView.on('afterTableReload', updateFloating);

});
-Saymaad

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts:1757
Joined: 2018-04-01 10:12

Re: sum column in select rows

Post by pbottcher » 2026-04-02 08:33

Hi,

you can try this and adopt it to your needs. Replace TABLENAME-FIELDNAME with our data.

Put the code into the hooks/TABLENAME-tv.js

Code: Select all

  function buildSumNotification() {
    var $ph = $j('.notifcation-placeholder');
    if (!$ph.length) return null;

    var $existing = $j('#selectedSumAlert');
    if ($existing.length) return $existing;

    $ph.append(
      '<div id="selectedSumNotice" class="alert alert-info" style="display:none; margin-bottom:10px;">' +
        '<strong>Selected:</strong> <span id="selectedCount">0</span> &nbsp; ' +
        '<strong>Sum:</strong> <span id="selectedTotal">0</span>' +
      '</div>'
    );
    return $j('#selectedSumAlert');
  }

  function formatNumber(n) {
    // set outputformat
    return new Intl.NumberFormat('en', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(n);
  }

  function getRowCheckboxes() {
    return $j('table tbody input[type="checkbox"]');
  }

  function getSelectedCheckboxes() {
    return getRowCheckboxes().filter(':checked');
  }

  // CHANGE selector to your numeric column cell
  function getValueFromRow($row) {
    var raw = $row.find('.TABLENAME-FIELDNAME a').text().trim();  
    // adjust if you need to convert your numberformat, e.g. german to english
    // raw = raw.replace(/\./g, '').replace(',', '.').replace(/[^\d.-]/g, '');
    var val = parseFloat(raw);
    return isNaN(val) ? 0 : val;
  }

  function updateNotification() {
    var $selected = getSelectedCheckboxes();
    var count = $selected.length;
    var total = 0;

    $selected.each(function () {
      var $row = $j(this).closest('tr');
      total += getValueFromRow($row);
    });

    $j('#selectedCount').text(count);
    $j('#selectedTotal').text(formatNumber(total));

    if (count > 0) {
      $j('#selectedSumNotice').show();
    } else {
      $j('#selectedSumNotice').hide();
    }
  }

  function initSelectedSumNotification() {
    buildSumNotification();

    // remove old handlers if any
    $j(document).off('change.selectedSumWatcher');

    // listen to row + header checkboxes
    $j(document).on(
      'change.selectedSumWatcher',
      'table tbody input[type="checkbox"], thead input[type="checkbox"]',
      function () {
        setTimeout(updateNotification, 0);
      }
    );

    updateNotification();
  }

$j(function() {
  initSelectedSumNotification();
})
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

User avatar
baudwalker
Veteran Member
Posts:191
Joined: 2015-02-03 08:08
Location: Bellingen NSW Australia

Re: sum column in select rows

Post by baudwalker » 2026-04-06 00:54

Great, that you to both pbottcher and saymaad I am tide down with other things at the moment, I will try these scripts and let you know me finding in the near future.
once again that you for the prompt responses.

Barry

User avatar
baudwalker
Veteran Member
Posts:191
Joined: 2015-02-03 08:08
Location: Bellingen NSW Australia

Re: sum column in select rows

Post by baudwalker » 2026-04-06 01:38

As both pbottcher and saymaad were so prompt in their replies I thought it was only fitting I apply their codes ASAP and reply just as prompt. I will have to say that both codes worked perfectly as I required. But with saymaad's code I was able to have the required result/sum in a floating box as I scroll down the table where pbottcher's was fixed at the top of the table.

Thank you to both

Barry

Post Reply