1,804 articles and 14,687 comments as of Wednesday, March 23rd, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Tuesday, January 6, 2009

JQuery for Everyone: Total Calculated Columns

Problem:  SharePoint will not perform “Totals” (Settings > Edit View) on a Calculated Column.

Solution:  Use jQuery to create an array, do the math with JavaScript, and insert the value in the Totals row.

To use this script, edit your view to use “Totals” on at least one column in your list.  Edit the view’s page and add a Content Editor Web Part (CEWP).  Insert the following script in the Source Editor adjusting the col variable as needed (col = 4 above).

Update: Therese commented on this article and had a great idea–make it work with groups. I did some research and came up with a single snippet that does it all with no script configuration.

With the new script, configure your list to display your calculated column that needs totaling last. I did this mainly because grouped rows have an additional, hidden column for the exact same list and I didn’t want to update the script between views.

One note on a view with groups: you will not have an “overall total” because the data does not exist on the page until the group opens. This would cause the “overall total” to only equal the total of visible groups which does not match how the other Total functions work.

(UPDATED!).

Original recipe:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function addCommas(nStr) {//formats number
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
$(function() {//sums money in specific list column
	var col = 4; //which column to sum
	var m = "$"; //change to "" for non-money format
	var arrayList = $("table.ms-listviewtable:first> tbody:eq(2)> tr").find(">td:eq("+col+")").get();
	var x = 0;
	var p1 = "";
	var p2 = "";
	$.each(arrayList, function(){
		x += Number($(this).text().replace(/\$|,|\)/g, "").replace(/\(/g,"-"));
	});
	if (x < 0) {//format for negative numbers
		p1 = "(";
		p2 = ")";
		x = Math.abs(x);
	}
	$("#aggr> tr:first> td:eq("+col+")")
		.css("text-align","right")
		.html("<b>Total = "+p1+m+addCommas(x.toFixed(2))+p2+"</b>");
});
</script>

New, with grouping support:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function addCommas(nStr) {//formats number
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function CalcGroup(groupName) {//sums money in specific list column
	var x = 0;
	var m = "";
	var p1 = "";
	var p2 = "";
	if (groupName == '') {
		$("table.ms-listviewtable:first> tbody:eq(2)").attr("id","tbod");
	}
	var arrayList = $("#tbod"+groupName+"> tr")
					.find(">td:last").get(); //array for groups
	$.each(arrayList, function(i,e){
		x += Number($(e).text().replace(/\$|,|\)/g, "").replace(/\(/g,"-"));
		if ($(e).text().indexOf("$") >= 0) {	m = "$" };
	});
	if (x < 0) {//format for negative numbers
		p1 = "(";
		p2 = ")";
		x = Math.abs(x);
	}
	if (arrayList.length > 0) {
		$("#aggr"+groupName+"> tr:first> td:last")
			.css("text-align","right")
			.html("<b>Total = "+p1+m+addCommas(x.toFixed(2))+p2+"</b>");
	}
}
//rewrite of WSS function
function ExpGroupRenderData(htmlToRender, groupName, isLoaded)
{
	var tbody=document.getElementById("tbod"+groupName+"_");
	var wrapDiv=document.createElement("DIV");
	wrapDiv.innerHTML="<TABLE><TBODY id=\"tbod"+groupName+"_\" isLoaded=\""+isLoaded+"\">"+htmlToRender+"</TBODY></TABLE>";
	tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
	if (CalcGroup) {
		CalcGroup(groupName+"_");
	}
}
$(function() {
	CalcGroup('');
});
</script>

Paul Grenier

View all entries in this series: PaulGrenier-JQuery for Everyone»
Entries in this series:
  1. JQuery for Everyone: Accordion Left Nav
  2. JQuery for Everyone: Print (Any) Web Part
  3. JQuery for Everyone: HTML Calculated Column
  4. JQuery for Everyone: Dressing-up Links Pt1
  5. JQuery for Everyone: Dressing-up Links Pt2
  6. JQuery for Everyone: Dressing-up Links Pt3
  7. JQuery for Everyone: Cleaning Windows Pt1
  8. JQuery for Everyone: Cleaning Windows Pt2
  9. JQuery for Everyone: Fixing the Gantt View
  10. JQuery for Everyone: Dynamically Sizing Excel Web Parts
  11. JQuery for Everyone: Manually Resizing Web Parts
  12. JQuery for Everyone: Total Calculated Columns
  13. JQuery for Everyone: Total of Time Differences
  14. JQuery for Everyone: Fixing Configured Web Part Height
  15. JQuery for Everyone: Expand/Collapse All Groups
  16. JQuery for Everyone: Preview Pane for Multiple Lists
  17. JQuery for Everyone: Preview Pane for Calendar View
  18. JQuery for Everyone: Degrading Dynamic Script Loader
  19. JQuery for Everyone: Force Checkout
  20. JQuery for Everyone: Replacing [Today]
  21. JQuery for Everyone: Whether They Want It Or Not
  22. JQuery for Everyone: Linking the Attachment Icon
  23. JQuery for Everyone: Aspect-Oriented Programming with jQuery
  24. JQuery for Everyone: AOP in Action - loadTip Gone Wild
  25. JQuery for Everyone: Wiki Outbound Links
  26. JQuery for Everyone: Collapse Text in List View
  27. JQuery for Everyone: AOP in Action - Clone List Header
  28. JQuery for Everyone: $.grep and calcHTML Revisited
  29. JQuery for Everyone: Evolution of the Preview
  30. JQuery for Everyone: Create a Client-Side Object Model
  31. JQuery for Everyone: Print (Any) Web Part(s) Plugin
  32. JQuery for Everyone: Minimal AOP and Elegant Modularity
  33. JQuery for Everyone: Cookies and Plugins
  34. JQuery for Everyone: Live Events vs. AOP
  35. JQuery for Everyone: Live Preview Pane
  36. JQuery for Everyone: Pre-populate Form Fields
  37. JQuery for Everyone: Get XML List Data with OWSSVR.DLL (RPC)
  38. Use Firebug in IE
  39. JQuery for Everyone: Extending OWS API for Calculated Columns
  40. JQuery for Everyone: Accordion Left-nav with Cookies Speed Test
  41. JQuery for Everyone: Email a List of People with OWS
  42. JQuery for Everyone: Faster than Document.Ready
  43. jQuery for Everyone: Collapse or Prepopulate Form Fields
  44. jQuery for Everyone: Hourly Summary Web Part
  45. jQuery for Everyone: "Read More..." On a Blog Site
  46. jQuery for Everyone: Slick Speed Test
  47. jQuery for Everyone: The SharePoint Game Changer
  48. JQuery For Everyone: Live LoadTip
 

Please Join the Discussion

96 Responses to “JQuery for Everyone: Total Calculated Columns”
  1. AutoSponge says:

    @Terry,

    You shouldn’t have to edit anything. You need to have at least one column of your list using a Totals function (like count on the Title column).

  2. larry says:

    I was trying to implement this on a list that has several calculated columns. Every time I add the array of column numbers I causes the script to error. is there an easy way to convert this to apply to several columns?

  3. AutoSponge says:

    @Larry,

    Neither was tested with multiple calc columns. After this example, I moved to a more reliable model for several calculations, see my project here: (http://owsapi.codeplex.com)

  4. Jason says:

    Anyone know how to do this on 2010 yet?

  5. JohnnyM says:

    Hi Paul, thanks for this post!

    However! I want to modify the concept a little bit.
    I want to create a page that only displays the totals and nothing else.

    I have been trying to do this in a DVWP with xsl but the iterative nature of the xsl:value-of select is restricting me to ‘current row’ so i cannot total. Basically, just show your Sum= Average= and Total= lines on a page.
    Any idea? Should I post this to STP?

  6. AutoSponge says:

    @JohnnyM,

    I actually had some of those same requirements which lead me to make the owsapi ( http://owsapi.codeplex.com ). It gives you a robust set of methods to perform math on a list’s values. The other benefit is that you can get those values and push them into another solution (like a graph API).

  7. AutoSponge says:

    @Jason,

    I’ll look into it as soon as I see a copy of 2010.

  8. JohnnyM says:

    Wow, I saw that post the other day, but guess I didn’t really pay attention. So, I just downloaded and am testing.

    THANK YOU PAUL!!!

    I see there are only 177 downloads, cant understand why not more.

    EVERYONE ELSE… Go get http://owsapi.codeplex.com It will set you FREE, like Yoga!

  9. JohnnyM says:

    Hey Paul, I have a custom list with a Yes/No column, There are 20 rows of data in the list and 10 are Yes and 10 are No. When I apply ‘Totals’ to the AllItems View I get a nice Count=10 at the top of the view. This ‘Count=#’ is just what I want to get into a webpart.
    I am trying ows.getSum(o.ctx,’Question One’); But that wont work. i get ‘undefined’.
    Do I need to filter that column?
    Any ideas?

  10. AutoSponge says:

    @JohnnyM,

    Do you get “o is undefined” ? If so, try the following in Firebug:

    owsapi();
    console.log(ows.getSum('ctx1','Question One'));
    

    If that works, it’s your function that you used to set the context variable. o.ctx only means something when in a callback function (function(o){…).

    Outside of a callback, you have to provide the context. Luckily, when viewing a standard list view web part, it’s always ‘ctx1′.

    Yes/No data appears as 0, 1, or undefined. The getSum method can skip over undefined values, so you should get your sum even when no values are defined (result = 0). So no, you shouldn’t have to filter the column.

  11. JohnnyM says:

    Duh, that was it. My context was defined for a callback function. Thank you.
    Now it returns the requested value as advertised!
    So, now I’ll get this to pass all column’s values to an array and populate a table or something.

    Thanks again.

  12. P.Venkateswara Rao says:

    Hi,

    Is there any limitation that a perticular group should have these many number of item ? Because I’m having 123 items in a single group. I used the above code and I’m getting Total=NaN. Please do some favour.

    Regards,
    Rao.

  13. AutoSponge says:

    @P.Venkateswara Rao,

    NaN (not a number) usually means you’re including data that can not be parsed as a number. Make sure you counted the columns correctly. Make sure you included columns like the file attachment that you don’t normally see data in.

  14. P.Venkateswara Rao says:

    Hi,
    Thanks for the responce. I observed one thing that, When items in a group exceeds 100 it will give more message at the end of that group, which makes the problem. Because if I clcik more option then I’m redirecting to the 101 to another 100’s count. In this one I’m able to see the Sumation of the Column. I checked from 1 to 100 it also giving correct value. But in grouping, if items greater that 100 giving this type of problem. Is it possible to increase the number of items should display more that 100 item. May be we can do it by Designer. Any Suggestion please.

    Thanks,
    Rao.

  15. AutoSponge says:

    @Rao,

    If that’s true, it’s another reason to use owsapi (http://owsapi.codeplex.com) or web services over this method.

  16. mlv289 says:

    This is great. How about if I wanted the group averaged instead of totaled?

  17. AutoSponge says:

    @mlv,

    Change line 36:
    .html(”Total = “+p1+m+addCommas(x.toFixed(2))+p2+”“);

    to

    .html(”Avg = “+p1+m+addCommas(x.toFixed(2)/arrayList.length)+p2+”“);

  18. mlv289 says:

    @AutoSponge

    Thanks! This is working, but actually appears it is giving me a lower number than it should. I checked the same numbers manually and then on excel – the SP list is giving me about 6 points lower… Any ideas as to why?

  19. mlv289 says:

    I think I understand what it is doing, but not sure how to fix the code. It looks like it adding an extra 2 to divide by the total – the extra two lines being the first grouping and then the 1st total column that is the out of the box function. So it should be just dividing the actual records, but instead is dividing by lines within the grouping…

  20. mlv289 says:

    @Paul

    Okay I got it… I am sure you would have gotten this in about 2 seconds, but here it is for anyone who is not js savvy yet. Just needed to add in some extra math.

    .html(”Avg = “+p1+m+addCommas(x.toFixed(2)/(arrayList.length-2))+p2+”“);

    Just had to add in the minus 2 on the array length. Can you confirm this is normal … not just some weird list I have going on?

  21. Daren says:

    I’ve added the grouping totals to the CEWP that has one calculated field (SqFt+0) however nothing is being displayed…not even an error message. Any help would be appreciated.

  22. Frank says:

    Hi,

    I’ve successfully got this working on the All Items view, but when I’m trying to add it to a grouped view, it displays Sum=NaN.

    If I try to print (i.e. alert) the value, I see that the grouping value itself is printed. In your example above, this would print Rate: $90.00 (2).

    Do you know what could be wrong?

    • Darryl says:

      @Frank

      Did you work out how to fix your Sum=Nan problem? I am having the same issue, so if you have a fix can you please let us know?

  23. LP says:

    How do I modify the script if I want to total on a sub-group? I’m getting javacript errors in IE8 when I try to expand a collapsed sub-group. It just says “Loading…”

  24. Jon says:

    When I try to change the code to average instead of sum, the total disapears from the page. Any suggestions as to why this might be happening?

    Thanks,
    J.E.S.

  25. AutoSponge says:

    @Jon,

    I’d have to see the modifications but you may have a syntax error. Open in Firebug and check the error log.

  26. darsh says:

    it rocks man!

  27. Reana says:

    I am also having problems with getting the Average to show – just shows nothing. The script for the Total does work. Anyone figure it out? Very noob :)

  28. Hello, When I try to use this script I can only get it to work when I set the data type of the calculated field to currency US-dollar, when I try to set it to Swedish it shows Nan, when I set it to Number it also shows Nan, when I set it to US-dollar it shows the vaule divided by 1000 so 1682 = 1.68

    What could be wrong?

  29. bolitasPH says:

    This one is helpful..it shows total sum but one question..

    how to handle if it consist of pagination?

    like 1-100 view and 101 to 200..

    The total only gets all the row of the specified column that is display.but if you click the next which is 101 to 200 the total sum will change to that specific page.

    Any solution on this matter?

  30. bolitasPH says:

    how about if it consist of pagination like 1-100 display for page 1 and 101 to 200 display for page 2 and so on..

    problem is when you cange the page the sum will also change.any solution on this matteR?

  31. ivan says:

    I’m hoping you can lead me in the right direction. I have a list that I need to chart. It goes like this:

    product line sold

    product A 100
    product B 200
    product A 50

    I have to get the totals per product, but have them in such a way that I can do a bar chart on the totals per product. Is that possible? Any hints you can provide?

  32. Charles says:

    Very cool, now how can this be combined with http://www.endusersharepoint.com/2009/04/29/finally-dynamic-charting-in-wss-no-code-required-part-3-multiple-pie-charts/ to chart the totals in a % pie…

    Thanks,
    Charles,

  33. Geoffrey says:

    Hi,

    I am trying to make a total of hours with minutes.
    Could you please quickly explain me the “replace” part of this line :

    x += Number($(this).text().replace(/\$|,|\)/g, “”).replace(/\(/g,”-”));

    this is the format of my calculated column : h:mm.

    Thank you,

    Geoffrey

  34. Karen says:

    Hello – I implemented this solution to a 2007 Sharepoint Site and it worked perfect. Then I tried in a 2010 Sharepoint site and nothing happens. Did anyone figure out how to do this in Sharepoint 2010. I do not have access to change any masterpages, sharepoint designer or add anything to the server. The solution to add a content editor webpart is perfect, why does it not work in 2010

    Thanks for the help
    Karen

  35. Fabiano says:

    Hello all!

    This works great for me, in the standard “All itens” list page… But, I need to put this Jquery script in a page with TWO list web parts.

    The list which I want to calculate some Totals is the second one in that page (from top to bottom), and in this scenario the script does nothing. If I move that list web part to the top of the page, along with the CEWP containing the script, it starts working. But, for application layout purposes, I need to place another list web part before this main list.

    I’m trying to figure out what I need to modify in the Jquery script… Any help will be very appreciated!!

    Thanks!!

  36. Tati says:

    Hello!
    I want to understand why a negative value is not displayed on Total.
    Eg. line 1 = -540
    line 2 = 60
    Total displays 480 instead of -480.
    How can I fix it?
    Thanks in advance.

Trackbacks

Check out what others are saying about this post...
  1. [...] Eric commented on my last article and [basically] issued another challenge. Will this work for time [...]

  2. [...] Anyone developing solutions around List View web parts may find this helpful. A common request from users involves performing various math functions on calculated columns. OOB, SP does not do this which lead me to develop code like Total Calculated Columns. [...]

  3. How to Total Calculated Columns in a SharePoint List…

    A customer recently approached us with the following problem: How can one Total (sum, average, Max, Min…

  4. [...] column” which normally presents Sharepoint a problem. Luckily i came across this this post to help [...]

  5. [...] column with groups on the page with the groups closed. SharePoint does not do this OOB and my previous attempt at a solution needed data rendered (groups [...]

  6. [...] JQuery for Everyone: Total Calculated Columns (49) [...]




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!