Script API Tutorial

Duplicating column captions in «Matrix» question

Sometimes it makes sense to copy the column caption inside matrix question and insert it into the middle of the table. It’s useful if your table is too big and Respondents have to scroll down in order to see all rows.

There are two matrix questions in the example below. The first question is displayed in the original format while for the second one we will apply the script that clones the column captions and inserts them after every 10 rows.

Besides, in order to highlight those column captions we will change their original style.

Give it a try

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

Create two "Single answer matrix" questions. Turn off "Answer required" check box in the first question for the sake of simplicity.

Launch the Script Editor in the second question and insert the following script into "OnRender script" tab (see the image below):

  • var tables = new Array();
  • $('.survey-matrix-question').each(function(index) {
  • var newClass = 'myMatrix'+index;
  • $(this).addClass(newClass);
  • tables.push(newClass);
  • });
  • var tablesLength = tables.length;
  • for (var i = 0; i< tablesLength; i++) {
  • var currentTable = tables[i];
  • var firstTr = $('.'+currentTable+' tr:first');
  • firstTr.css("background-color","BackColor");
  • firstTr.css("color","Color");
  • $('.'+currentTable+' td').each(function(index) {
  • $(this).css("border-color","BorderColor");
  • $(this).css("border-style","solid");
  • $(this).css("border-width","2px");
  • });
  • var counter = 0;
  • var inserAfterRequestes = new Array();
  • $('.'+currentTable+' tr').each(function(index) {
  • if (counter==InsertAfter) {
  • inserAfterRequestes.push(index);
  • counter=0;
  • }
  • counter++;
  • });
  • var length = inserAfterRequestes.length;
  • var insertedNumber = 0;
  • for (var j = 0; j<length; j++) {
  • var index = inserAfterRequestes[j];
  • index = index + insertedNumber;
  • var request = '.'+currentTable+' tr:eq('+index+')';
  • var cloneOfColumns = firstTr.clone();
  • cloneOfColumns.insertAfter($(request));
  • insertedNumber++;
  • }
  • }

After that modify the tokens highlighted in red as described in the table below:

BackColor Background color of the column captions. You can type in the color names (like “green” or “black”) or the “hex” codes (e.g. #ccccff)
Color Color of the text in column captions
BorderColor Color of the borders (applicable to the whole table)
InsertAfter The number of rows after which the copy of the column captions will be inserted. For example, if you want the column caption to be duplicated every 15 rows you need to set this parameter to 15