0

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

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

enter image description here

  • 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? – user68133 Jun 22 '17 at 23:30
  • Try this totalsRow.find("td:eq(" + colIndex + ")").text(sumOfVals).css("style","text-align:right"); – Venkat Konjeti Jun 23 '17 at 0:49
  • I tried that and tried override using css but no luck – user68133 Jun 23 '17 at 13:37
  • Thanks! I figured it out! I used this instead- <style> td, th { padding: 2px 12px 2px 4px; } </style> – user68133 Jun 27 '17 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.