2

So I'm getting my listItems with a Camlquery, but i want to calculate the avg of the "price" rows

This is the code I've used so far:

function VisaLista() {
    namn = document.getElementById("txtNamn");
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
    "<Where>" +
    "<And>" +
    "<Eq><FieldRef Name='Title'/><Value Type='Text'>" + namn + "</Value></Eq>" +
    "<Or>" +
    "<Eq><FieldRef Name='Prioritet'/><Value Type='Text'>Hög</Value></Eq>" +
    "<Eq><FieldRef Name='Status'/><Value Type='Text'>Startad</Value></Eq>" +
    "</Or>" +
    "</And>" +
    "</Where>");
    listItems1 = list.getItems(camlQuery);
    clientContext.load(listItems1);
    clientContext.executeQueryAsync(OnSuccessVisa, OnFail);
}
function OnSuccessVisa() {
    var listEnumerator = listItems1.getEnumerator();
    var elmt = 0;
    while (listEnumerator.moveNext()) {
        var currentItem = listEnumerator.get_current();
        elmt = (currentItem.get_item('_x0072_zb6'));

        var sum = 0;
        for (var i = 0; i < elmt.length; i++) {
            sum += parseInt(elmt[i], 10);
        }

        var avg = sum / elmt.length;

        document.write("The sum of all the elements is: " + sum + " The average is: " + avg);
    }
    $("#Kategori1").text = "Medelvärdet för dessa ordrar: " + avg
}

I am getting following error

"Cannot get the value length of null - at elmt, line 43

  • so what is the problem you are facing? don't just put the code put error or issues you facing – Akshay Randive Jun 4 '15 at 9:38
  • @inferno I'm getting "Cannot get the value length of null - at elmt, line 43 – Dr Cox Jun 4 '15 at 9:40
  • @Somethingcool123 length property is used for arrays, you have declared elmt = 0 and setting value from item. I doubt it will ever have length. – Asad Refai Jun 4 '15 at 9:53
2

You need fix it as below

function OnSuccessVisa() {
    var listEnumerator = listItems1.getEnumerator();
    var count = listItems1.get_count();
    var sum = 0;

    while (listEnumerator.moveNext()) {
        var currentItem = listEnumerator.get_current();
        var elmt = currentItem.get_item('_x0072_zb6');
        if(elmt != null)
            sum += parseInt(elmt, 10);  
    }

    if(count > 0)
    {
        var avg = sum / count;
        alert("The sum of all the elements is: " + sum + " The average is: " + avg);
        $("#Kategori1").text("Medelvärdet för dessa ordrar: " + avg);
    }
}
1

Try to debug in browser console if you are receiving proper object, check for the null object before you access its property

while (listEnumerator.moveNext()) {
        var currentItem = listEnumerator.get_current();
        elmt = (currentItem.get_item('_x0072_zb6'));
        if(elmt != null && elmt !== undefined){
        var sum = 0;
        for (var i = 0; i < elmt.length; i++) {
            sum += parseInt(elmt[i], 10);
        }

        var avg = sum / elmt.length;

        document.write("The sum of all the elements is: " + sum + " The average is: " + avg);
    }
  • I'm still getting the same error, cannot Failed to load resource: the server responded with a status of 403 (Forbidden) App.js:43 Uncaught TypeError: Cannot read property 'length' of null – Dr Cox Jun 4 '15 at 9:51
  • are you using this in SP apps? have you given your app appropriate permissions – Akshay Randive Jun 4 '15 at 9:52
1

There are more ways to skin a cat
(not that I am into skinning cats)

Drawback of the scripting method it has to be wired up on each View webpart you want to use it and doesn't work on SP2010 if you're using 2013 JCSOM code.

It is possible to stuff (javascript)code in a Calculated Column which does this calculation.

This: http://www.viewmaster365.com/#/Create/Sum
(step by step instructions on the site)

Does this:

It works in every location/View the Column is displayed, no need for JSlink connections.

With all the code in one Calculated Column:

="<div style=""color:"
 & IF(    [Rate]<[Buy]   ,"red","green")
 & """>"
 & DOLLAR(   [Qty]*[Rate]   )
 & "</div>"
 & "<div class=""vmSums"" style=""display:none;font-weight:bold;border-top:1px solid black;""></div>"
 & "<img src=""/_layouts/images/blank.gif"" onload=""{"
 & "var TBODY=this.parentNode.parentNode.parentNode.parentNode"
 & ",dataSum='data-vmSum',dataCnt='data-vmCount',total=value="
 &    [Qty]*[Rate]   
 & ",count=0;"
 & "if(TBODY.getAttribute(dataSum)){"
 & "total=parseFloat(TBODY.getAttribute(dataSum))+value;"
 & "count=~~TBODY.getAttribute(dataCnt)+1}"
 & "TBODY.setAttribute(dataSum,Number(Math.round(total+'e2')+'e-2').toFixed(2));"
 & "TBODY.setAttribute(dataCnt,count);"
 & "window.clearTimeout(window.vmSumFunc);"
 & "window.vmSumFunc=window.setTimeout((function(){"
 & "var lastrownr=~~TBODY.getAttribute(dataCnt),"
 & "last=document.getElementsByClassName('vmSums').item(lastrownr),"
 & "total=parseFloat(TBODY.getAttribute(dataSum)).toFixed(2);"
 & "last.textContent='$'+total;"
 & "last.style.display='block';"
 & "}), 100)"
 & "}"">"

All you have to do is rewrite the Sum calculation to an average, all data is available.
I haven't had my second cup of coffee yet; so don't blame if the the change requires more than:

 & "last.textContent='$'+total/count;"

This method has its own drawbacks as documented on the ViewMaster365 site; but is less programming, doesn't need VS or Designer and works on SP2010 as well.

CalcMaster Bookmarklet to edit Formulas

It is a PITA to debug Calculated Columns. Because you don't get feedback until you save a Formula and you end up having to click multiple times to get back to your Formula.

I have written a small 'CalcMaster' bookmarklet which hooks into the formula-editor and does a save of the Formula on every keypress; giving immediate feedback.
Just published a first version yesterday on GitHub:

https://github.com/Danny-Engelman/CalcMaster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.