Sum of sub answer

From Catglobe Wiki
Revision as of 10:24, 10 October 2018 by Administrator (talk | contribs)
Jump to: navigation, search

This solution will help your answer will total 100%.

First create a textgrid question, then add the below script to Javascript tab
2018-06-05 15-33-27.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-06-05 15-03-25.png