3

Using Survey JS, the idea is to ask users to answer a number of questions from a pre-defined list of options (radio buttons).

Each option will be allocated a score (0, 25, 75, 100), as each selection is made i'd like to display the live score somewhere on screen.

I know I need to create an expression like in this example, but i'm not sure where to start.

I've created the basic structure of the form, can be seen here.

$.material.init();

var json = {
  title: "Audit Example",
  showProgressBar: "top",
  pages: [{
    questions: [{
      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"
      }]
    }]
  }
  ]
};

Survey.defaultBootstrapMaterialCss.navigationButton = "btn btn-green";
Survey.defaultBootstrapMaterialCss.rating.item = "btn btn-default my-rating";
Survey.Survey.cssType = "bootstrapmaterial";

var survey = new Survey.Model(json);

survey.onComplete.add(function(result) {
  document.querySelector('#result').innerHTML = "result: " + JSON.stringify(result.data);
});

survey.render("surveyElement");

Any advice is appreciated.

TheOrdinaryGeek
  • 2,273
  • 5
  • 21
  • 47
  • Could you please describe what you want to achieve? Is computing the sum of elements causing any trouble? Or you want it to work interactively like in example? – mpasko256 Dec 14 '18 at 16:55

1 Answers1

3

Let assume your question is to display sum of elements dynamically.

To do so, you can register your own function like:

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);

And then use it like:

}, {
    "type": "expression",
    "name": "total",
    "title": "Total Quality:",
    "expression": "sumInObject({Quality})",
    "displayStyle": "decimal",
    "startWithNewLine": true
}

Full code in Plunk

Hope that it would help.

mpasko256
  • 811
  • 14
  • 30