Randomly draw value from array using JavaScript; access as field variable | XM Community
Skip to main content

Hi all,
I am trying to randomly draw an entry from an array (using JavaScript) and then access this later in the question text.
For this, I included the following JS in the welcome page:
Qualtrics.SurveyEngine.addOnload(function()
{   // initialize random gender (3x)
   function randGend() {
      var gendArray = g'Male', 'Female']; // initialize array of genders to choose from
      var randGender = gendArrayG(Math.random() * gendArray.length) | 0]; // randomly choose gender
      return randGender; }
   var genderPlayer11 = '0'
   genderPlayer11.push(randGend()); // save a random gender
   var genderPlayer12 = '0'
   genderPlayer12.push(randGend()); // save a random gender
   var genderPlayer13 = '0'
   genderPlayer13.push(randGend()); // save a random gender as genderPlayer1
   Qualtrics.SurveyEngine.setEmbeddedData("genderPlayer11", genderPlayer11); // make available
   Qualtrics.SurveyEngine.setEmbeddedData("genderPlayer12", genderPlayer12); // make available
   Qualtrics.SurveyEngine.setEmbeddedData("genderPlayer13", genderPlayer13); // make available
});
I'm new to JavaScript but what I tried to accomplish here is to write a function that draws randomly from gendArray, and apply it three times, saving the results as e.g. "genderPlayer11" (which should contain each either "Male" or "Female"). I then (using "Qualtrics.SurveyEngine.setEmbeddedData(...);") tried to make this available to Qualtrics to use later on.

In a next step, on another screen, I'm trying to display this as text, e.g. "The person is rgenderPlayer11]" etc.
For this, I have included the following code in the question before I want to access genderPlayer11:

Qualtrics.SurveyEngine.addOnload(function()
{
   var genderPlayer11 = "${e://Field/genderPlayer11}"; // make available
   var genderPlayer12 = "${e://Field/genderPlayer12}"; // make available
   var genderPlayer13 = "${e://Field/genderPlayer13}"; // make available
});
The text in the text box on Qualtrics then is: "The person is ${e://Field/genderPlayer11}." However, when I look at the survey (using both "Publish" or "Preview"), the display reads "The person is ." (i.e. the variable is not found).
Can someone point me to the right direction or point out my mistake (I'm not sure if I'm making a JavaScript or a Qualtrics mistake)? Many thanks in advance!

In your first script:
genderPlayer11.push(randGend());
throws an error because genderPlayer11 isn't an array. Instead you can replace that line and the one above it with:
var genderPlayer11 = randGend();


Leave a Reply