Pergunta

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.

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top