How do I calculate a total sum field in a SPList? I want it to automatically add up the sum of a column that user inputs as a total field in the bottom. For example, a list will contain numbers 10, 20, 30, and the bottom will display 60.
1 Answer
Out of the box, there is no solution to sum the values in the column. So I have used JavaScript to achieve that.
This script requires the field name you want to sum on the list view page. But the drawback is it sums the values on the current page. I am not sure this will help your scenario.
<script type="text/javascript">
$(document).ready(function() {
var fieldName = "Vacation_x0020_Start"; //name of the field to sum
var colIndex = -1;
var colCount = 0;
var sumOfVals = 0;
colCount = $(".ms-listviewtable thead th").length;
$(".ms-listviewtable thead th").each(function(index) {
if($(this).find('div[name="' + fieldName + '"]').length > 0){
colIndex = index;
}
});
$(".ms-listviewtable tbody tr").each(function(){
var colValue = $(this).find("td:eq("+colIndex+")").text();
if(colValue != "") {
sumOfVals = sumOfVals + parseInt(colValue);
}
});
var totalsRow = $("<tr>");
for(var i=0; i<colCount; i++) {
totalsRow.append($("<td>"));
}
totalsRow.find("td:eq(" + colIndex + ")").text(sumOfVals);
$(".ms-listviewtable tbody").append(totalsRow);
});
</script>
This script has been added to the Script Editor web part on the same list view page.
The output looks like as follows
-
Thanks! This is exactly what I needed. How do I move the total 300 to the right a bit? I did inspect element and did typed in <td class="ms-cellstyle ms-vb2">300</td> and it moved it on the browser but it is showing up as <td></td>. Is there a way to override this? Commented Jun 22, 2017 at 23:30
-
Try this
totalsRow.find("td:eq(" + colIndex + ")").text(sumOfVals).css("style","text-align:right");
Commented Jun 23, 2017 at 0:49 -
-
Thanks! I figured it out! I used this instead- <style> td, th { padding: 2px 12px 2px 4px; } </style> Commented Jun 27, 2017 at 17:38