Script for making a text grid numerical summing to a specific value

From Catglobe Wiki
Jump to: navigation, search

Challenge

In order to validate the inputs of a text grid question
As a questionnaire creator
I want to check if the sum of all values equals to a specific value

Solution

  • Create a text-grid question, accept the numberical for sub question
  • Add the below script to that question

Code

 1 var expectedTotal = 100;
 2 function specialQuestionCheck()
 3 {
 4    var msg = "";
 5    var val = 0;
 6    for(i = 0; i < quest.questions.length; i++)
 7    {
 8       var tmpVal = document["query"][quest.questions[i].label].value;
 9       if(tmpVal == "")
10       {
11          // NOPI
12       }
13       else if(isNaN(tmpVal))
14       {
15          msg += "- Angiv venligst et  tal\n";
16       }
17       else if (tmpVal<0 || tmpVal>100)
18       {
19          msg += "Værdier skal være fra 0 til 100";
20       }
21 	  else
22 	  {
23 		val += parseFloat(tmpVal);
24 	  }
25    }
26 
27    if(msg == "")
28    {
29       if(val == expectedTotal)
30       {
31          return true;
32       }
33       else
34       {
35          alert("Værdierne skal summe til "+ expectedTotal +" - nuværende sum: " + val);
36          return false;
37       }
38    }
39    else
40    {
41       alert("Følgende fejl opstod:\n"+msg);
42       return false;
43    }
44    return false;
45 }
46 
47 var defaultQuestionCheck = questioncheck;
48 
49 function newGoNext()
50 {
51    document["query"]["dir"].value = "next";
52    if(defaultQuestionCheck())
53       return specialQuestionCheck();
54    else
55       return false;
56 }
57 
58 quest.next = newGoNext;

Source

Questionnaire Resource Id on cg.catglobe.com site: 164079 (Question: Q11_Script_for_making_a_text_grid_numerical_summin)