Script API Tutorial

Total sum answer validation in «Open-ended» question

In the example below we are asking Respondent how he/she would spend 10 000 USD. We will add several alternatives between which our Respondent should distribute that amount of money.

After the answers are given, we will check if total sum is equal to 10 000, and if it’s not, the Respondent will not be able to proceed to the next question.

Besides, our example will demonstrate how to validate that Respondent entered the numbers (not characters or symbols) into our "Open Ended" question.

In order to reproduce this example, please undertake the following steps:

Create an "Open Ended" question with several alternatives. Open Script Editor and insert the following script into "OnValidate script" tab (see the image below):

  • var comparedSum = amValue;
  • var answers = this.get();
  • var totalSum = 0;
  • for (var i = 0; i<answers.length; i++) {
  • var answer = answers[i];
  • var answerValue = answer.value;
  • if (isNaN(answerValue)){
  • return "Please, type the number in the \'"+answer.alternative.name+"\' field";
  • }
  • totalSum = totalSum + parseInt(answerValue);
  • }
  • if (totalSum!=comparedSum) {
  • return "Total sum must be equal to "+ comparedSum;
  • }

Replace amValue by the sum to be distributed. In our example we are talking about money in the amount of 10 000 USD, so this value should be set to '10000' (do not use space for separation!).

Advanced explanations

  • var comparedSum = amValue;
  • // declare variable which contains amount of money
  • var answers = this.get();
  • // get answers of the question
  • var totalSum = 0;
  • // counter of entered sum
  • for (var i = 0; i<answers.length; i++) {
  • var answer = answers[i];
  • // we iterate over the answers
  • var answerValue = answer.value;
  • // and save value for each answer
  • if (isNaN(answerValue)){
  • // if the value is not a number..
  • return "Please, type the number in the \'"+answer.alternative.name+"\' field";
  • ///then we raise exception message. Note, that this message is a concatenated string which is formed from static and dynamic parts.
  • Static parts are: "Please, type the number //in \'" and "\' field" which do not change. Dynamic part is the name of specific alternative. We take this name using "answer.alternative.name".
  • }
  • totalSum = totalSum + parseInt(answerValue);
  • // increase the counter of entered sums by the value entered. Before adding value to the total sum we convert it from string to number
  • }
  • if (totalSum!=comparedSum) {
  • // check whether the total sum is equal to the amount of money in our question
  • return "Total sum must be equal to "+ comparedSum;
  • // if it’s not, then raise exception message. Note again, that raised message is formed dynamically
  • }

Learn more at CoolTool knowledge base