Reply To: Using Javascript to Performa Calculation and display at the top of each column

Forums General discussion Using Javascript to Performa Calculation and display at the top of each column Reply To: Using Javascript to Performa Calculation and display at the top of each column

#13890
Alexander Bautz
Keymaster

Hi,
I though you would have both values in the list header, but with the “Days taken” not being summed up, I guess the best approach is to use a query that is not depending on the actual items in the view. Put this code in a Script editor web part in the page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
setTimeout(function(){
	(function(){
		jQuery.ajax({       
			"url": _spPageContextInfo.webServerRelativeUrl+"/_api/web/lists/GetById('"+_spPageContextInfo.pageListId.split(/{|}/).join("")+"')/items?$filter=MOCNumber ne null",   
			"type": "GET",   
			"contentType": "application/json;odata=verbose",
			"headers":{ 
				"Accept": "application/json;odata=verbose",
				"X-RequestDigest" : jQuery("#__REQUESTDIGEST").val()
			},   
			"success": function(data){
				var totItems = data.d.results.length, totDays = 0, avgDays = 0;
				jQuery.each(data.d.results,function(i,item){
					totDays += Number(item.DaysTaken);
				});
				avgDays = totDays / totItems;
				jQuery("table.ms-listviewtable").before("<div style='color:green;font-size:22px;border:1px #cccccc solid;padding:3px;'>Average days: "+parseInt(avgDays,10)+"</div>")
			},
			"error":function(err){
				console.log(err);
			}
		});
	})();
},1000);
</script>

The filter on the query is set in the “url” parameter behind the “filter=”. Change this to match the filter you need to use.

You also need to ensure you have the correct FitldInternalName of your fields in the “MOCNumber” and “DaysTaken” columns.

This code will show a count as shown in the screenshot.

Let me know if you have any questions.

Please note that this code snippet if for SharePoint 2013 – if you need it for SP2010 I have to rewrite it slightly.

PS: None of the columns need to actually be in the view.

Hope you can use this approach.

Alexander

Attachments: