Archive for May, 2010

05/06/10
Fahad Zia

Running Total in SharePoint List using jQuery


Create a list with 2 columns:
1. Amount (Number)
2. Running Total (Calculated Column) with Formula

=CONCATENATE("<span class='test'>",Amount,"</span>")

. This is a place holder for the running total
3. Now add some data to the list and your list will look like the screenshot below:
runningtotal1
As you can see the calculated formula is showing html. We need to change this html text to be part of page DOM using javascript. I will do this using jQuery
4. Add Content Editor Web Part to this page and in Source Editor put the following script:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">
var $j=jQuery.noConflict();
$j(document).ready(function()
{

 //convert html text to DOM elements
 $j(".ms-vb2:contains('<span')").each(function(intIndex){
 var tempSpan = document.createElement("span");
 tempSpan.innerHTML = $j(this).text();
 $j(this).text("");
 $j(this).append(tempSpan);

  });

 //reference DOM elements created in the above loop and calculate running total
 $j(".test").each(function(intIndex){
 //add previous .ms-vb2 values if intIndex >0
 if (intIndex >0)
 {
  //alert(intIndex);
  var i = intIndex-1;
  var previousTotal= $j(".test:eq(" + i + ")").text();
  //alert("previous Total=" + previousTotal);
  var currentCellValue = $j(this).text();
  //alert("currentCellValue=" + currentCellValue);
  $j(this).text(parseInt(previousTotal) + parseInt(currentCellValue));
 }

 }); 
});
</script>

Save and view the page:

runningtotal2

NOTE: THIS WONT CARRY TOTALS WHEN PAGING IS NEEDED/BROWSED. If you want the running totals to work with paging consider creating a custom webpart and use DataTable to acheive this which should work in any scenario.