Skip to content

Instantly share code, notes, and snippets.

@Dmitri-Sintsov
Created August 4, 2024 10:57
Show Gist options
  • Save Dmitri-Sintsov/1f5262299f80cb89e71094fcaaaef26a to your computer and use it in GitHub Desktop.
Save Dmitri-Sintsov/1f5262299f80cb89e71094fcaaaef26a to your computer and use it in GitHub Desktop.
Sum of table rows in Javascript and format cell numbers.
function prettify (num, separator) {
var n = (typeof num === "string") ? num : num.toString();
var sep = typeof separator === "undefined" ? " " : separator;
return n.replace(/(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g, "$1" + sep);
}
// SUMM TABLE ROWS
function sumTableRows() {
var table = document.getElementById("mainTab");
let lastRow = table.rows[table.rows.length - 1];
for (var i = 1; i < table.rows.length - 1; i++) {
let row = table.rows[i];
for (var j = 1; j < row.cells.length; j++) {
let cel = row.cells[j];
lastRow.cells[j].innerText =
(Number(lastRow.cells[j].innerText) || 0) +
(Number(cel.innerText) || 0);
cel.innerText = prettify(cel.innerText);
}
}
for (var i = 1; i < lastRow.cells.length; i++) {
let cel = lastRow.cells[i];
cel.innerText = prettify(cel.innerText);
}
}
$(document).ready(function() {
sumTableRows();
});
var table = $.parseHTML(
`<table id="mainTab" style="width:100%" class="table table-striped table-bordered">
<thead>
<tr>
<th>А</th>
<th>Н</th>
<th>О</th>
<th>З</th>
<th>И</th>
</tr>
</thead>
<tbody>
</tbody>
</table>`
);
var rows = $.parseHTML(response.html);
$(table).find('tbody').append($(rows));
$(table).find('tr:last').after('<tr><th>Итого</th><th></th><th></th><th></th><th></th></tr>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment