Reverse single grid between sub questions and answer options
Challenge
Client would like to show Sub-Questions and Answer Options inversly on Single-Grid. Therefore, we have to reverse the columns and rows on Single-grid. By the way, we have to change the radio buttons accordingly.
Example
We have the original Single Grid like this:
After reversing, we have a Single Grid like this:
Solution
1. Reverse Sub-Questions' names and Answer Options' names. 2. Rearrange the radio buttons accordingly.
Code
1 // CODE EXAMPLE: CHANGE COLUMN AND ROW
2
3 quest.onInit = function()
4 {
5 // declare variables
6 var mytable = $("table[class='grid_inner']");
7 var numberOfQuestions = this.questions.length;
8 var numberOfAnswers = quest.questions[1].options.length;
9 // get max number of Answer Option and Sub Question
10 var maxValue = numberOfQuestions;
11 if (numberOfAnswers > numberOfQuestions)
12 {
13 maxValue = numberOfAnswers;
14 }
15 // get all radio buttons in the Grid
16 var radioButtonsEven = $("td[class='grid_subquestion_even']");
17 var radioButtonsOdd = $("td[class='grid_subquestion_odd']");
18
19 // ~~~~~~`swap column to row and inversely~~~~~~
20 // Rearrange radio buttons
21 var myRow = mytable.find("tr:first").next();
22 var evenRunner = 0;
23 var oddRunner = 0;
24
25 // Swap AnswerOption names and Sub Question names
26 for(var i=1; i <= maxValue; i++ )
27 {
28 var aoIndex =i;
29 var sqIndex =i;
30 var aoName = "td[id='grid_answeroption_text_" + aoIndex +"']";
31 var sqName = "td[id='grid_subquestion_text_" + sqIndex +"']";
32 var ao=$(aoName);
33 var sb=$(sqName);
34 var checkLenghtCondition = ((ao.length>0) && (sb.length>0));
35 if (checkLenghtCondition)
36 {
37 sb.parent().prepend(ao);
38 mytable.find("tr:first").append(sb);
39 }
40 else{
41 // insert new row
42 if ((sb.length==0))
43 {
44 mytable.append($("<tr>").append(ao).remove());
45 }
46 else
47 {
48 mytable.find("tr:first").append(sb);
49 }
50 }
51 }
52 // swap radio buttons
53 for (var i=0; i<numberOfQuestions; i++)
54 {
55 myRow = mytable.find("tr:first");
56 for (var j=0; j< numberOfAnswers; j++)
57 {
58 myRow = myRow.next();
59 if (i%2==0)
60 {
61 if (myRow.length==0){
62 mytable.append($("<tr>").append(radioButtonsEven[evenRunner]));
63 }
64 else
65 {
66 myRow.append(radioButtonsEven[evenRunner]);
67 evenRunner = evenRunner + 1;
68 }
69 }
70 else
71 {
72 if (myRow.length==0){
73 mytable.append($("<tr>").append(radioButtonsOdd[oddRunner]));
74 }
75 else
76 {
77 myRow.append(radioButtonsOdd[oddRunner]);
78 oddRunner = oddRunner + 1;
79 }
80 }
81 }
82 }
83
84
85 }