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
sum column in select rows
- baudwalker
- Veteran Member
- Posts:191
- Joined: 2015-02-03 08:08
- Location: Bellingen NSW Australia
Re: sum column in select rows
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
Simple Configuration
At the top of the script, you will find a config section where you can easily customize how it behaves:
Just copy the code into your
-Saymaad
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:
- fieldName: Set this to the name of the column you want to sum (like 'balance').
- decimalPlaces: Control how many numbers appear after the decimal point.
- 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. - showTotal/showAverage: Toggle these to
trueorfalseto choose which stats to display, (bonus if you want min / max /avg). - numberFormats: The script is already set up to handle various global formats like 1,234.56 or 1.234,56 automatically.
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);
});
Re: sum column in select rows
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
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> ' +
'<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.
- baudwalker
- Veteran Member
- Posts:191
- Joined: 2015-02-03 08:08
- Location: Bellingen NSW Australia
Re: sum column in select rows
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
once again that you for the prompt responses.
Barry
- baudwalker
- Veteran Member
- Posts:191
- Joined: 2015-02-03 08:08
- Location: Bellingen NSW Australia
Re: sum column in select rows
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
Thank you to both
Barry
