Calculating the Average of Survey Item Answers
When your survey answers have numeric saved values you might have a situation where you want to calculate the average of all the choices the user selected.
Included here is a javaScript function that can be used to accomplish that task.
The function is in the Settings...Events
//get the average from the survey item app.getSharedData().getAverageFromSurvey = function (surveyItem) { var avg = 0; for(var i=0; i<surveyItem.getLength(); i++) { //get the value of the question var qval = surveyItem.get(i).getValue(); if(qval !== "") { avg += parseInt(qval); } } return (avg / surveyItem.getLength()); }
The usage of the function is in the onItemChange of the survey item:
var surveyQList = page.F_Survey.getChildren(); BO.F_Number4.setValue(app.getSharedData().getAverageFromSurvey(surveyQList));
The F_Survey is the ID of the survey item whose average is being calculated.
The F_Number is the ID of the field where the average is being placed.
A few assumptions have been made for this function:
1. The average is taken on all the questions in the survey item whether they are answered or not. You could modify the function if you wanted to only take the average of "answered" questions, however I assume that all the questions would be answered, which is why I didn't implement it.
2. The saved value of the survey item choices must be numbers. The function doesn't check and may produce a strange result if you tried this with non-numeric saved values.