Sum of sharepoint list items in particular field - javascript

I have one list with cost field,and I have multiple items in my list .I have to get the sum of cost field in my aspx page. If I add new item then also the aspx page should calculate the sum of cost field ...how can i achieve it using javascript...anyone please help me...

You could use OOB sum feature for your list view.
Demo:
Or, load list items and then calculating by JSOM script.
Demo:
window.onload=function (){
var url=_spPageContextInfo.webAbsoluteUrl;
var ctx = new SP.ClientContext(url);
var TotalCost=0;
//Get the web
var web = ctx.get_web();
//Get the List based upon the Title
var list = web.get_lists().getByTitle("Store Items");
//The Query object. This is used to query for data in the List
var query = new SP.CamlQuery(); ctx.load(list);
query.set_viewXml('<View></View>');
var items = list.getItems(query);
//Retrieves the properties of a client object from the server.
ctx.load(list);
ctx.load(items);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var currentListItem = enumerator.get_current();
//console.log(currentListItem.get_item("Price"));
TotalCost+=currentListItem.get_item("Price");//cost field
}
console.log("-------------------------------")
console.log("TotalCost:"+TotalCost);
}),
Function.createDelegate(this, fail)
);
}
function fail(){
console.log("fail")
}

You can use the below Java script code from the asp.net application, after connecting to the the SharePoint list through the context object, need to get the list items. You can refer the below Java script code to do the sum up functionality.
for (var i = 0; i < monthChoices.length; i++){
chartSeries[i] = [];
var monthTotal = 0;
for(var j= 0; j< arrItems.length; j++ ){
if(monthChoices[i]==arrItems[j].get_item("Month") && arrItems[j].get_item("Duration")!= ""){
monthTotal += arrItems[j].get_item("Duration");
}
}
chartSeries[i].push([monthChoices[i], monthTotal]);
console.log(chartSeries[i]);
}
Reference URL :
SharePoint List : Sum of Column Values using JavaScript Client Object Model
Or
The below code :
function onItems(sender, e)
{
var iterator=myTotalTimeItems.getEnumerator();
var sum=0;
while(iterator.moveNext()){
var item=iterator.get_current();//retrieves current item from the collection.
var num=item.get_item("Estimated_x0020_Time_x0020__x002");
if(isNaN(num)) continue;
else
sum+=Number(num);
}
alert("Total estimated time:"+sum);
}
Reference URL :
https://social.msdn.microsoft.com/Forums/office/en-US/6370dbf7-4494-4d79-b02a-647f7442cc6e/sum-column-value-with-javascript?forum=sharepointdevelopment

If you want to display the sum value on a page, first create a 'Scripteditor' webpart on that page. You can do this by editing the page, clicking 'add a webpart', choose the 'Media and content' category and then selecting 'Scripteditor'.
Once it is created, edit the following code so the 'listName' variable contains the name of your list and I assumed here you have a column named 'Cost'. If your column name is different, change that also.
<p id="SumPrices"></p>
<script type="text/javascript">
var listName = 'LISTNAME';
var xhr = new XMLHttpRequest();
xhr.open('GET', _spPageContextInfo.webAbsoluteUrl + '/_api/web/lists/GetByTitle(\'' + listName + '\')/items?$select=Cost');
xhr.setRequestHeader('Accept', 'application/json; odata=verbose');
xhr.onload = function(){
if (xhr.status === 200) {
var results = JSON.parse(xhr.responseText);
results = results.d.results;
var sum = 0;
for (var i = 0; i < results.length; i++){
sum += results[i].Cost;
}
document.getElementById('SumPrices').innerText = sum;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
</script>
Now click on 'EDIT FRAGMENT' in the bottom right corner of the webpart (in edit page mode) and paste the code there. Click on 'Insert' and close the edit page mode. You will now see the sum of all the prices on your page.

Related

How do I use two variables in my function?

So I have multiple script. One script retrieves data from a Googlesheet and parses it as JSON. The other one uses this to output it to HTML.
My first:
function getStatistics() {
var sheet = SpreadsheetApp.openById("ID");
var rowsData = sheet.getRange("A:A").getValues();
var result = JSON.stringify(rowsData);
var funcNumber = 1;
return result;
}
This retrieves the data from a spreadsheet in column A.
The second script, here I want to use both 'Result' and 'Funcnumber' in my function.
function onSuccess(data, funcNumber) {
var dataJson = JSON.parse(data);
var newColumn = document.createElement("div");
newColumn.className = "column";
for(var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
Using the Json result to PARSE the HTML works. But retrieving 'funcNumber' from the function not. Then finally I call the first function with this line:
google.script.run.withSuccessHandler(onSuccess).getStatistics();
Does anybody know how to use both result and funcNumber in my second function?
function getStatistics() {
var ss = SpreadsheetApp.openById("ID");
const sheet = ss.getSheetByName('Sheet1');
let result = {data:JSON.stringify(sheet.getRange(1,1,sheet.getLastRow(),1).getValues()),funcNumber:1}
return result;
}
function onSuccess(obj) {
var dataJson = JSON.parse(obj.data).flat();
var newColumn = document.createElement("div");
newColumn.className = "column";
for (var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + obj.funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
A single column or row is still a 2d array
Following is the way to make the call in Google script to return the value for the 2nd parameter.
google.script.run
.withSuccessHandler(onSuccess)
.withUserObject(funcNumber)
.getStatistics()
WithUserObject() needs to be called after the withSuccessHandler.
See the documentation below on Google script
withUserObject(object)
Sets an object to pass as a second parameter to the success and failure handlers. This "user object" — not to be confused with the User class — lets the callback functions respond to the context in which the client contacted the server. Because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. User objects cannot, however, be objects constructed with the new operator.

ServiceNow auto-populate Script not being called

I have a table in ServiceNow that contains Store and a corresponding Tier that is associated with the Store.
I am trying to auto-populate a record producer, once Store is selected. and my script is not running.
The table is a custom table created in a scoped application which is new to me so not sure what I am doing wrong in the scripting. Any advice?
//Catalog Client Script (runs on [Store] Record Producer Change)
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// new GlideAjax object referencing store of AJAX script include
var ga = new GlideAjax("HRProfileAjax");
// add store parameter to define which function we want to call
// method store in script include will be getFavorites
ga.addParam("sysparm_store", "getHRProfile");
ga.addParam("sysparm_tier", "getHRProfile");
// submit request to server, call ajaxResponse function with server response
ga.getXML(ajaxResponse);
function ajaxResponse(serverResponse) {
// get result element and attributes
var result = serverResponse.responseXML.getElementsByTagstore("result");
var message = result[0].getAttribute("tier");
//check for message attribute and alert user
//if(message)
//alert(message);
//build output to display on client for testing
// get favorite elements
var favorites = serverResponse.responseXML.getElementsByTagstore("favorite");
for(var i = 0; i < favorites.length; i++) {
var store = favorites[i].getAttribute("store");
g_form.setValue(store);
var tier = favorites[i].getAttribute("tier");
//output += store + " = " + tier + "\n";
g_form.setValue(store,tier);
}
//g_form.setValue('number',output);
}
//Script #2 HR PROFILE AJAX
/*
* HRProfileAjax script include Description - sample AJAX processor returning multiple value pairs
*/
var HRProfileAjax = Class.create();
HRProfileAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
/*
* method available to client scripts call using:
* var gajax = new GlideAjax("HRProfileAjax");
* gajax.addParam("sysparm_store", "getFavorites");
*/
getHRProfile : function() {
// build new response xml element for result
var result = this.newItem("result");
var store = this.getParameter('store');
var hrPro = new GlideRecord('x_hiring_gri_hr_storetier');
hrPro.addQuery('store',store);
hrPro.query();
if(hrPro.next()){
result.setAttribute("message", "returning all favorites");
this._addFavorite("tier", hrPro.tier);
}
},
_addFavorite : function(store, value) {
var favs = this.newItem("favorite");
favs.setAttribute("store", store);
},
type : "HRProfileAjax"
});

How to retrieve multi-value Taxonomy Field from term store SharePoint online

I am trying to retrieve terms from term store using JavaScript, it work just a fine with this code:
Get the label of single taxonomy field:
var fieldValue = item.get_item("FieldName");
var fieldLabel = fieldValue.Label;
I have one issue to retrieve labels of a multi-value Taxonomy Field?
I've tried this
var fieldValue = item.get_item("FieldName");
var taxEnumerator = fieldValue.getEnumerator();
while(taxEnumerator.moveNext()){
var currentTerm = taxEnumerator.get_current();
var label = currentTerm.Label;
// do something with the label here
}
But it doesn't work
Most likely you are getting this error since sp.taxonomy.js library has not been loaded and in that case taxonomy field value is returned as "lightweight" object (not of SP.Taxonomy.TaxonomyFieldValueCollection object type).
Option 1 (recommended): getting getting multiple taxonomy field values with sp.taxonomy library
First of all, I would recommend this approach since SP.Taxonomy namespace provides not only a standard way for dealing with taxonomy field values but also a way of working with Managed Metadata API via JSOM.
The following example shows how to:
ensure sp.taxonomy.js library has been loaded
get multiple taxonomy field value which represents
SP.Taxonomy.TaxonomyFieldValueCollection object
Example:
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName);
for(var i = 0; i < fieldVal.get_count(); i++) {
var label = fieldVal.get_item(i).get_label();
var guid = fieldVal.get_item(i).get_termGuid();
//...
}
},
function(sender,args){
console.log(args.get_message());
});
});
Option 2: getting multiple taxonomy field values without sp.taxonomy.js library loaded
When sp.taxonomy library is not loaded, taxonomy field value could still be retrieved via _Child_Items_ property as demonstrated below:
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName)._Child_Items_;
for(var i = 0; i < fieldVal.length; i++) {
var label = fieldVal[i].Label;
var guid = fieldVal[i].TermGuid;
//...
}
},
function(sender,args){
console.log(args.get_message());
});

AngularJS Array Not Loading On View Load, but Alerts/Console Work

I am trying to push values into an array as follows, but it is showing as an empty array. Alerting works. I am sure I am missing something obvious. Any clues? I have included the code with the just the array push attempt and another entry of code that has working alerts.
$scope.termsArray = [];
execOperation();
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
}
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the code with working alerts:
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
var termList = "Terms: \n";
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
termList += currentTerm.get_id() + currentTerm.get_name() + "\n";
}
alert(termList);
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the HTML output:
<div> {{termsArray}}</div>
It returns []
Update: If I click in an input box and back out, or click an alert and hit ok, it then loads the array instead of loading on page load.
I was able to track the issue down. It appears that Angular doesn't respect non-Angular functions on load, so I needed to wrap the $scoped array in a $scope.apply. Please see here for details: Execute SharePoint Function On Page Load in AngularJS Application ($scope issue???)

Code to populate lookup doesn't fully work first time

I have some javascript code on my form that when the record is first being created it auto populates 2 lookup fields with the current user. This works fine most of the time but I've noticed that on the first time that I use it (per day/session?) the first field that I want to fill in does get populated however the field still looks empty, as if the code has not worked.
I've confirmed that the field is getting filled in and it is only the display for this field that isn't working, but I can't figure out why, especially why it is only the one field that this is happening with.
I will post the code I use below, when calling it I pass in an array of the field names that I want to set. Can anyone help me find out why this isn't working?
Thanks
function RetrieveUserInfo(fieldsToSet) {
//Retrieve user information
var context;
var serverUrl;
var UserID;
var ODataPath;
context = Xrm.Page.context;
serverUrl = context.getServerUrl();
UserID = context.getUserId();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var retrieveUserReq = new XMLHttpRequest();
retrieveUserReq.open("GET", ODataPath + "/SystemUserSet(guid'" + UserID + "')", true);
retrieveUserReq.setRequestHeader("Accept", "application/json");
retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveUserReq.onreadystatechange = function () {
SetUserValues(this, fieldsToSet);
};
retrieveUserReq.send();
}
function SetUserValues(retrieveUserReq, fieldsToSet) {
if (retrieveUserReq.readyState == 4
/* complete */
) {
if (retrieveUserReq.status == 200) {
var retrievedUser = this.parent.JSON.parse(retrieveUserReq.responseText).d;
if (retrievedUser.FullName != null)
//Get details of current user
var setUservalue = new Array();
setUservalue[0] = new Object();
setUservalue[0].id = Xrm.Page.context.getUserId();
setUservalue[0].entityType = 'systemuser';
setUservalue[0].name = retrievedUser.FullName;
//get form type
var formType = Xrm.Page.ui.getFormType();
if (formType != undefined) { //Create
if (formType == 1) {
//for each field specified, set it to the current user
for (var i = 0; i < fieldsToSet.length; i++) {
Xrm.Page.getAttribute(fieldsToSet[i]).setValue(setUservalue);
}
}
}
}
else {
}
}
}
This is a long shot, but the field that doesn't work - it doesn't happen to be a disabled field? If it's a readonly field you might have to add
Xrm.Page.getAttribute(“fieldname”).setSubmitMode(“always”);
on the onsave event.

Categories

Resources