x

JavaScript

Home > Coder’s Corner > JavaScript
Survey Research Suite

Guide

Customize your survey using JavaScript code to achieve effects beyond what are available within the Qualtrics tool or from HTML and CSS customizations.

Add JavaScript to Your Survey
  1. Click on the Question you would like to add JavaScript to. If the JavaScript will be applied to an entire page of the survey rather than just one question, select any question on the page of the survey to which you would like to apply the code.
  2. Click the purple Advanced Question Options drop-down box on the left of the question.
    Select Add JavaScript.
  3. Add your JavaScript directly below the line that says /*Place Your Javascript Below This Line*/.
Question API
Qualtrics created a Question API to make it easier for you to connect your JavaScript to Qualtrics. Click here to download our latest Question API documentation.

Example JavaScript

Add Disappearing Labels in a Text Box

This code allows you to insert question labels into your text that will disappear when the respondent clicks in the box. Click here to see an example.

JavaScript Code

    var InputId = $("QR~"+this.questionId);
    var Text = "your name";
    InputId.value = Text;
     
    InputId.onclick = clear;
    InputId.onblur = repopulate;
      
    function repopulate() {
    if (InputId.value == "")
    {
      InputId.value= Text;
    } 
    }
     
    function clear() {
    if (InputId.value == Text)
    {
      InputId.value= "";
    }
    }

Instructions

Place this code into the JavaScript editor for the question that you would like this to occur on.

Autopopulating Answer Choice Fields with Code

The tool now allows you to auto-populate answer choice fields without a JavaScript code by using the Default Choices Option, but if you are setting up a complex customization in your survey, this JavaScript may be useful to you.

With JavaScript, answer choices and text fields can be pre-populated when a respondent enters the survey. Click here to see an example.

Single Line Entry

    var InputId = $("QR~"+this.questionId);
InputId.value= "text goes here";

Form Text Entry

    this.setChoiceValue(1,"text goes here");

Multiple Choice – Single Answer and Multiple Answer

    this.setChoiceValue(1,true);

Multiple Choice – Drop Down Menu

   if($('QID1'))
{
$$('#QID1 select').each(function(s){
s.value = (s[s.length-1].value);
}) }

Matrix Table

  this.setChoiceValue(1,1,true);

Instructions

Single Line Text Entry
Paste the code into your JavaScript editor and change the text to be displayed as needed.

Form Text Entry
Paste the code into your JavaScript editor and change the text to be displayed as needed. Replace ’1′ with the row number of the form field into which you would like to place text.

Multiple Choice – Single Answer and Multiple Answer
Paste the code into the JavaScript editor and replace the 1 with the ID of whichever choice you would like to be preselected.

Multiple Choice – Dropdown List
Paste the code into the JavaScript editor. Replace QID1 with the correct question ID. Change the 1 in s.length-1 to reflect the position (from the bottom of the list) of the choice you would like preselected.

Matrix Table
Paste the code into the JavaScript editor. The first ’1′ represents the row of choice to be selected, and the second ’1′ represents the column.

Change Text Box Size and Area

This code enlarges the “Allow Text Entry” box and makes the entered text wrap.

JavaScript Code

   var te =$(this.questionContainer).getElementsByClassName('TextEntryBox');
  for(var i=te.length-1;i>=0;i--)
  {
    var s = te[i];
    var p = s.parentNode;
    var n = QBuilder('textarea',{name:s.name,className:'InputText'});
    n.innerHTML = s.value;
    Event.observe(n,'click',function(e){
      var el=Event.element(e);
      var en = el.getAttribute('name');
      $(en.substr(0,en.lastIndexOf("~"))).checked = true;
    });
    $(n).setStyle({width: '600px',height:'200px'});
    p.replaceChild(n,s);
  }

Instructions

Put this code into the code view of the question that contains your “Allow Text Entry” box. Adjust the size of the box by changing the numbers on the line that reads: “$(n).setStyle({width: ’400px’,height:’100px’});”

Constant Sum, Change the “Total” Tag

This code replaces the word “Total” with a description of your choice in a constant sum question. Click here to see an example.

JavaScript Code

var questionId = this.questionId;
 $(questionId+'_Total').up(1).getElementsByTagName('label')[0].innerHTML = "Total Years"

Instructions

Place this code in the JavaScript editor of your question. Change the words “Total Years” to fit your needs.

Constant Sum, Hide Zeros

This code will remove the zeros from a Constant Sum question so that all of the Text Entry boxes are blank. Click here to see an example.

JavaScript Code

var inputs = $(this.questionContainer).select('input');
inputs.each(function(el) {if (el.value == 0) el.value='';});

Instructions

Paste this code into the JavaScript editor of your question. No modification is needed.

Custom ‘Submit’ Button

This allows you to change the button text for a particular page of a survey without changing it for the entire survey. This may be useful if you want the last button in your survey to say ‘Submit’ instead of ‘Next.’ Click here to see an example.

Change Next Button Text

var newName = 'Submit';
if ($('NextButton').nodeName == 'INPUT')
{
$('NextButton').setValue(newName);
}
else if ($('NextButtonText').nodeName == 'SPAN')
{
$('NextButtonText').innerHTML = newName;
}
else // next button is probably a button
{
$('NextButton').innerHTML = newName;
}

Change Back Button Text

var newName = 'Submit';
if ($('PreviousButton').nodeName == 'INPUT')
{
$('PreviousButton').setValue(newName);
}
else if ($('PreviousButtonText').nodeName == 'SPAN')
{
$('PreviousButtonText').innerHTML = newName;
}
else // previous button is probably a button
{
$('PreviousButton').innerHTML = newName;
}

Instructions

On the line with var newName, change the “Submit” text to whatever you prefer the button to say. Paste the code into the JavaScript editor of any question on the page that contains the button you would like to change.

Insert Text Before or After a Text Box

This code will insert a character or text before any type of Text Entry box. For instance, if you were asking how much money a participant spent in a given category, you might want a dollar sign before the text box. Click here to see an example.

JavaScript Code

For placing the character before any textbox:

var questionId = this.questionId;
var inputs = $(questionId).getElementsByTagName('input');
for(var x = 0; x<inputs.length;x++){
var input = inputs[x];
if(input.id != undefined && input.type =='text')
{
  var id = input.id;
  $(id).up().innerHTML = "$ " + $(id).up().innerHTML;
}}

JavaScript Code

For placing the character after any textbox:

var questionId = this.questionId;
var inputs = $(questionId).getElementsByTagName('input');
for(var x = 0; x<inputs.length;x++){
var input = inputs[x];
if(input.id != undefined && input.type =='text')
{
  var id = input.id;
  $(id).up().innerHTML = $(id).up().innerHTML + "$ ";
}}

Instructions

Insert this code into the JavaScript editor of your question. Replace the dollar sign (the one surrounded by quotation marks) with your text or character(s).

Add subheadings in a Matrix Table

JavaScript Code

Group your statements together by putting headings into your Matrix Table. Works for Likert, Bipolar, and Profile. Will not work for Rank Order, Constant Sum, and Text Entry.

$('QR~QID12~1~1').style.display='none';
$('QR~QID12~1~2').style.display='none';
$('QR~QID12~1~3').style.display='none';
$('QR~QID12~1~4').style.display='none';
$('QR~QID12~1~6').style.display='none';

Instructions

Items you will need for this to take effect:

  1. QID# – Go to Account Settings and click Qualtrics IDs. Find and click the survey name, then find the question and grab the ID to the right of the question (QID#). This will take the place of “QID12″ in the example.
  2. Row # of Matrix (…~1~…) – You will need to count which row of radio/checkbox buttons it is you want to hide. The first row starts as “1″. This will replace the “~1″ in the example.
  3. Radio/Checkbox Button number (…~1′…) – Most individuals want to hide the entire row. The button on the left starts at 1 and each one to the right increments one.
Use Keystrokes to Answer Questions

With this code, participants can answer a question and move to the next page by pressing a key on a keyboard. When combined with a Timing Question, this is an optimal way to run many types of reaction time studies. Click here to see an example.

JavaScript Code

    if ($('NextButton'))
    $('NextButton').hide();
    if ($('PreviousButton'))
    $('PreviousButton').hide();

    var that = this;
    Event.observe(document,'keydown',function(e){
    var choiceID = null;
    if (e.keyCode == 74) //'j' was pressed
    {
    choiceID = 1;
    }
    else if (e.keyCode == 75) //'k' was pressed
    {
    choiceID = 2;
    }
    if (choiceID)
    {
    that.setChoiceValue(choiceID,true);
    that.clickNextButton();
    }
    });
   

Instructions

To activate key stroke submission, paste this into the Javascript Editor of your question. The numbers 74 and 75 are the html code numbers for the j and k keys. To use different key strokes, you can find the appropriate numeric codes at this site:

http://rmhh.co.uk/ascii.html

Auto-Advance on Choice Selection

With this code, participants can answer a question and be moved to the next page automatically. This code is intended only for a multiple choice question with a single question on the page.

JavaScript Code

For Single Answer Multiple Choice Question, please use the following code:

 this.questionclick = function(event,element){ 
// 
if (element.type == 'radio') 
{ 
this.clickNextButton();
} 
}

For Multiple Answer Multiple Choice Question, please use the following code:

 this.questionclick = function(event,element){ 
// 
if (element.type == 'checkbox') 
{ 
this.clickNextButton();
} 
}

Instructions

To activate automatic on-click advance, paste this into the JavaScript Editor of your question.