melimoo
melimoo

Reputation: 3

Generating random number that will not repeat between surveys in Qualtrics using javascript

A disclaimer: I'm not familiar with Javascript. I've merely cobbled together a basic understanding of what I need to do for this task from Stack Overflow and other resources. My apologies if something below is unclear.

My problem: I need to generate a random number between 0 and 8,764, using Javascript, that will not repeat itself between Qualtrics survey responses.

Currently, I've found code to create an array that contains all numbers between 0 and 8,764, shuffles the array, and pops the last number off the end of the array. It then adds embedded data to Qualtrics with that popped number, and I can then pipe the embedded data into a Qualtrics question to display it to my survey respondent. See below:

Qualtrics.SurveyEngine.addOnReady(function()
{

for (var i = 0, ar = []; i < 8; i++) {
ar[i] = i;
}

ar.sort(function () {
  return Math.random() - 0.5;
});

var randomnumber = ar.pop();

Qualtrics.SurveyEngine.addEmbeddedData("randomnumber", randomnumber);

});

However, as far as I can tell, this Javascript code "resets" itself between survey responses, meaning it will re-create and re-shuffle the array each time a new respondent enters the survey. I'd like to find a way to make it so that it will be impossible for a new respondent to see the same popped "randomnumber" as a previous respondent. So, if the first survey respondent saw a 1, then the next survey respondent could see any number besides a 1 (let's say they see a 100 instead), and the next respondent could see any number except a 1 or a 100, etc etc.

I think it's possible to use embedded data in Javascript code and manipulate it (see here). It seems like there might be a way to access the randomnumber embedded data and write Javascript code to not remove any numbers from the array that match one of the previously popped randomnumbers. I lack the technical knowledge to execute this, if it's even the best way to accomplish the task.

Any and all help appreciated!

Upvotes: 0

Views: 1907

Answers (1)

T. Gibbons
T. Gibbons

Reputation: 5004

You can do what you want with Advanced Randomization in Qualtrics.

Set up a multiple choice question with your numbers 0 through 8,764 as the choices. Then use Advanced Randomization to select a random subset of 1 from all the numbers and click "Evenly Present" (Evenly Present is what tells Qualtrics to use every number before reusing any). Use JavaScript to hide the multiple choice question:

$(this.questionId).hide();

Now you can pipe your unique random number into a subsequent question. For example:

${q://QID1/ChoiceGroup/DisplayedChoices}

Upvotes: 2

Related Questions