JavaScript Question API

Introduction

The JavaScript Question API is a set of pre-written JavaScript methods designed to make it easier for you to integrate your own custom code into a survey.

There are five key tasks in the JavaScript Question API –

  • Embedded Data: Translate the variables in your JavaScript into data fields that are saved in the survey results.
  • Piped Text: Retrieve answers to previous questions and use those in your JavaScript functions.
  • Event Listening: Run code once a user has interacted with a survey question in a specific way.
  • Answer Choices: Check the currently selected answer choice, or use your JavaScript function to dynamically select an answer choice.
  • Survey Progression: Control when a participant switches between pages within the survey.

Getting Started

All methods and functions described below (with the exception of Piped Text), will need to be wrapped in a Qualtrics.SurveyEngine.addOnload function to properly run. Code placed within this function can reference methods of the Qualtrics Question API using the this keyword.

this.clickNextButton();
The above code snippet would not run properly, because “this” has not been defined.
Qualtrics.SurveyEngine.addOnload(function ()
{
     this.clickNextButton();
});
With the addOnload function running, this line of code can now be properly evaluated.

If you are inserting your code using our built-in JavaScript editor, you will see we already include the appropriate addOnLoad function.

Embedded Data

One of the primary uses of JavaScript in Qualtrics is to take variables you’ve created and save them in a format Qualtrics recognizes – Embedded Data. The method below is used to save JavaScript variables as Embedded Data. To have this Embedded Data reported in your survey results, you’ll also need to define it in your Survey Flow.

setEmbeddedData(field name, field value)

setEmbeddedData takes two parameters – the name of the Embedded Data field you’d like to update, and the value you’d like to save to this field.

Qualtrics.SurveyEngine.addOnload(function ()
{
     var participantNumber = Math.floor((Math.random()*1000000)+1);
     Qualtrics.SurveyEngine.setEmbeddedData("ParticipantNumber",participantNumber);
});
Qtip: While Qualtrics is forgiving with Embedded Data variable names, JavaScript is not so much. For any Embedded Data fields being used for JavaScript, we recommend avoiding spaces and special characters.

Need to retrieve Embedded Data for use in an equation rather than set it? Continue reading below to learn how to do this using Piped Text.

Piped Text

JavaScript functions often require knowing answers participants have given to previous questions in the survey. This is where Piped Text comes in.

Piped Text is a string that represents an answer participants have provided in the survey, or an Embedded Data field you have saved. Piped Text is typically used in the survey itself to customize the text of questions. It can also be used in your JavaScript.

The naming convention for Piped Text includes //. Because this is also the syntax for a comment in JavaScript, Piped Text cannot be inserted directly into the JavaScript editor.

var finalAnswer = ${q://QID2/ChoiceGroup/SelectedChoices} + 3;
In the above example, all code following the // in the Piped Text is treated as a comment, resulting in errors in the code execution.

To use Piped Text, first save it as a string variable, and then reference that variable name later in your code.

var selectedChoice = "${q://QID2/ChoiceGroup/SelectedChoices}";
var finalAnswer = selectedChoice + 3;

Event Listening

Often functions you write should not run until the participant has interacted with a question. The questionclick function can be used to listen for a user interacting with your question. The function will be passed the following parameters:

  • event: Will always be equal to click.
  • element: The element that was clicked. Possible values for the “type” property of this element are [text, radio, checkbox, undefined].
Qualtrics.SurveyEngine.addOnload(function ()
{
    this.questionclick = function(event,element){
		if(element.type == "checkbox"){alert("Good job choosing an answer!");}
    }
});

Event Listening is commonly used in conjunction with the last two JavaScript tasks – selecting and checking answer choices, and controlling survey progression. For example, you may want to automatically progress to the next page of the survey once the user has clicked on a specific answer choice.

Answer Choices

The next common JavaScript task is to work with answer choices, either using JavaScript to select answer choices, or using JavaScript to check which answers have already been selected.

Some methods in this section require you know the ID of the choice you are referencing. This ID can be found using the Inspect Element feature on your preferred browser, and finding the HTML ID of the Input field for the answer choice. The following screenshot shows where you find the Question ID, Choice ID, as well as Sub ID (where applicable) in this HTML ID.

Locate Choice ID

setChoiceValue ( Choice ID, [Sub ID], value )

Sets the actual value of a choice in the question. If a matrix-style question, also specify the Sub ID.

Qualtrics.SurveyEngine.addOnload(function ()
{
     /*Selects the third choice in a Multiple Choice question*/
     this.setChoiceValue(3,'true');

     /*Selects the third choice in the second row of a Matrix Table question*/
     this.setChoiceValue(2,3,'true');

     /*Enters 'Hello World' into a Text Entry field*/
     this.setChoiceValue('TEXT','Hello World');

     /*Enters 'Hello World' into the second box in a Text Entry Form*/
     this.setChoiceValue(2,'Hello World');

     /*Enters '32' into the second box in a Constant Sum question*/
     this.setChoiceValue(2,32);
});

setChoiceValueByRecodeValue ( Recode Value, [Sub ID], value )

In addition to the Choice ID, each choice includes a coded value which you, the survey builder, can set. This coded value can be used in place of the Choice ID to select an answer choice.

Qtip: Multiple choices in a question may have the same coded value. An attempt will be made to set each choice that is found. For single answer questions this may result in only the last matching choice being set.
Qualtrics.SurveyEngine.addOnload(function ()
{
     /*Selects choices with a recode value of 3*/
     this.setChoiceValueByRecodeValue(3,'true');

     /*Selects choices with a recode value of 3 in the second row of a Matrix Table question*/
     this.setChoiceValueByRecodeValue(3,2,'true');

     /*Enters '32' into any boxes with a recode value of 2 in a Constant Sum question*/
     this.setChoiceValueByRecodeValue(2,32);
});

setChoiceValueByVariableName ( Variable Name, [Sub ID], value )

In addition to the Choice ID, each choice includes a variable name which you, the survey builder, can set. The variable name will be equal to the text of the answer choice, unless an alternate variable name has been specified in the Recode Values menu. This variable name can be used in place of the choice ID to select an answer choice.

Qualtrics.SurveyEngine.addOnload(function ()
{
     /*Selects choices with a variable name of 'Red'*/
     this.setChoiceValueByVariableName(‘Red’,'true');

     /*Selects choices with a variable name of 'Red' in the 2nd row of a Matrix Table question*/
     this.setChoiceValueByVariableName('Red',2,'true');

     /*Enters '32' into any boxes with a variable name of ‘Red’ in a Constant Sum question*/
     this.setChoiceValueByVariableName('Red',32);
});

getChoiceValue ( Choice ID , [Sub ID] )

getChoiceValue will return the actual value of a given choice. This value will be ‘true’ if the choice has been selected, ‘false’ if it hasn’t, or for open-ended questions, the text entered by the participant. This method is used to retrieve the value of the current question. To retrieve the value of a previous question, use Piped Text.

Qualtrics.SurveyEngine.addOnload(function ()
{
     this.getChoiceValue(3); //returns the value of choice 3
     this.getChoiceValue(3,2); //returns the value of row choice 3 answer col 2
});

Survey Progression

The JavaScript Question API includes a set of methods than can be used to control when Next and Previous buttons appear in the survey and when a user switches pages. Note that most timing-based survey progression can be handled using the Timing question type. The Question API is only needed when you have more complex requirements for survey progression.

clickNextButton()

Emulates clicking the Next Button to progress to the next page of the survey.

Qualtrics.SurveyEngine.addOnload(function ()
{
     // When the visitor selects an answer choice (clicks one of the radio buttons), 
     // move automatically to the next page of the survey.
     this.questionclick = function(event,element){ 
          if (element.type == 'radio') 
          { 
               this.clickNextButton();
          } 
     }
});

clickPreviousButton()

Emulates clicking the Back Button to return to the previous page of the survey.

Qualtrics.SurveyEngine.addOnload(function ()
{
     // If the visitor selects the first choice ("I need to review my answers"), 
     // click the Previous Button.
     this.questionclick = function(event,element){ 
          if (this.getChoiceValue(1) == 'true') 
          { 
               this.clickPreviousButton();
          } 
     }
});

disableNextButton() and enableNextButton()

Hide or show the Next Button.

Qualtrics.SurveyEngine.addOnload(function ()
{
     // Hide the Next Button. Show it again when the user selects 
     // the first answer choice ("I agree to the terms and conditions") 
    $('NextButton') && $('NextButton').hide();
     this.questionclick = function(event,element)
	 { 
          if (this.getChoiceValue(1) === true) 
          { 
               $('NextButton') && $('NextButton').show();
      		}
	 }
});

disablePreviousButton() and enablePreviousButton()

Hide or show the Previous Button.

Qualtrics.SurveyEngine.addOnload(function ()
{
     // Hide the Previous Button. Show it again when the user selects 
     // the first answer choice ("I need to review my answers") 
     this.disablePreviousButton();
     this.questionclick = function(event,element){ 
          if (this.getChoiceValue(1) == 'true') 
          { 
               this.enablePreviousButton();
          } 
     }
});
Google+