Difference between revisions of "Sum of sub answer"

From Catglobe Wiki
Jump to: navigation, search
(Tag: visualeditor)
 
Line 1: Line 1:
 
This solution will help your answer will total 100%.
 
This solution will help your answer will total 100%.
  
First create a textgrid question, then add the below script to Javascript tab<br/>
+
First create a textgrid question, then add the below script to Javascript tab<br />
[[File:2018-06-05 15-33-27.png|774x774px]]
+
[[File:2018-10-10 16-15-53.png|774x774px]]
  
 
<source lang="javascript">
 
<source lang="javascript">
Line 48: Line 48:
 
</source>
 
</source>
  
[[File:2018-06-05 15-03-25.png|774x774px]]
+
[[File:2018-10-10 16-17-08.png|719x719px]]
  
 
[[Category:Questionnaire]]
 
[[Category:Questionnaire]]

Latest revision as of 10:26, 10 October 2018

This solution will help your answer will total 100%.

First create a textgrid question, then add the below script to Javascript tab
2018-10-10 16-15-53.png

//
// Private helper functions
//
function sumUp(question) {
   // Sum up all except the last sub question, which is used for the s
   var sum = 0;
   question.subQuestions.slice(0, question.subQuestions.length - 1).each(function(sq) {
      sum += parseInt(sq.attr('answer')) || 0;
   });
   return sum;
}

//
// Add an extra row to contain the sum
//
Question.bind('afterShowQuestion', function(ev, question, jqe) {
   var sum = sumUp(question);
   var sumElt = jqe.find('tr:last input').prop('disabled', true).val(sum);
});

//
// Listen for changes to the answer and update the sum
//
Question.bind('answerChanged', function(ev, question, subQuestion) {
   // Ignore answer changes for the last sub question
   if (subQuestion.gridNumber == question.subQuestions.length - 1) {
      return;
   }
   question.subQuestions[question.subQuestions.length - 1].attr('answer', sumUp(question));
});

//
// Validate that the sum is exactly 100
//
Question.bind('afterValidateQuestion', function(ev, question, state) {
   var sum = sumUp(question);
   if (sum != 100) {
      state.valid = false;
      question.attr('errorMessage', 'Du bedes angive dine svar fra 0-100%, så dit svar tilsammen giver 100%');
   }
});

2018-10-10 16-17-08.png