<!DOCTYPE html>
<html>
<head>
<title>Calculate expression based on other answers - Expression question, jQuery Survey Library Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/jquery"></script>
<script src="https://surveyjs.azureedge.net/1.0.60/survey.jquery.js"></script>
<link href="https://surveyjs.azureedge.net/1.0.60/survey.css" type="text/css" rel="stylesheet"/>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="surveyElement"></div>
<div id="surveyResult"></div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
var json = {
"showQuestionNumbers": "off",
"elements": [
{
type: "matrix",
name: "Quality",
title: "Please score each department below.",
columns: [{
value: 0,
text: "None"
}, {
value: 25,
text: "Isolated"
}, {
value: 50,
text: "Some"
}, {
value: 100,
text: "Widespread"
}],
rows: [{
value: "training",
text: "Training"
}, {
value: "support",
text: "Support"
}, {
value: "safety",
text: "Safety"
}, {
value: "communication",
text: "Communication"
}]
}, {
"type": "expression",
"name": "total",
"title": "Total Quality:",
"expression": "sumInObject({Quality})",
"displayStyle": "decimal",
"startWithNewLine": true
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (result) {
document
.querySelector('#surveyResult')
.innerHTML = "result: " + JSON.stringify(result.data);
});
function sumInObject(params) {
if (params.length != 1) return 0;
if(!params[0]) return 0;
const object = params[0];
const array = Object.keys(object)
.map(key => object[key])
.map(value => parseInt(value));
return array.reduce((left, right) => left + right);
}
Survey.FunctionFactory.Instance.register("sumInObject", sumInObject);
$("#surveyElement").Survey({model: survey});