Generate random values using Javascript | XM Community
Solved

Generate random values using Javascript


I am using the below javascript to define an array and retrieve random elements from the array.

var COST = ["$400","$500","$600","$700","$800"];
var COST_a1 = COST[Math.floor(Math.random()*COST.length)];
alert (COST_a1) ; /* for debugging */

When I preview the survey, Qualtrics runs this piece of code TWICE. The alert box pops up twice with different values for COST_a1.
This is causing issues on another page when I try to capture the value of Cost_a1
using
this.setChoiceValue(3,COST_a1);
I only need the random value to be generated once. Any guidance on this matter is appreciated.
Thank you.
icon

Best answer by Michael_Campbell_RedPepper 27 March 2018, 21:53

View original

12 replies

Userlevel 4
Badge +3
Ah! Well, that is to be expected in this scenario. It's frustrating, but part of the system's functionality. One less intrusive way of debugging is using `console.log()` to display things in the Developer Console of your browser.
Userlevel 4
Badge +3
For sure! You can store it as an Embedded Data Field using this Javascript:

`Qualtrics.SurveyEngine.setEmbeddedData('FIELD', value);`
`Qualtrics.SurveyEngine.getEmbeddedData('FIELD');`

(I included the code for retrieving EDF's, too, just for kicks)
Do you mean add the following within addOnReady()
Qualtrics.SurveyEngine.setEmbeddedData('FIELD', value);
Qualtrics.SurveyEngine.getEmbeddedData('FIELD');

and how do I eventually get these values into the output. (Data & Analysis -> Export)
Michael, you are amazing!!! That solution works perfectly!! Thank you very much!!
Userlevel 4
Badge +3
Is this in the Preview Mode? The code runs for both the Mobile and Desktop versions of the code, independently.
Yes, this is in Preview mode. I am trying to test the survey.
Thank you for the info. Is there any way for me to capture the values that were 'randomly' picked out from the array ? I am needing these values for data analysis later.
Userlevel 4
Badge +3
That will show up in your Reporting Services.
Thank you Michael for the quick responses. I will give it a shot.
Out of curiosity, does the code execute twice only in Preview mode or even when I publish the survey.
Userlevel 4
Badge +3
Of course! And it should only execute it once. One thing I strongly recommend is keeping the code inside the Lifecycle methods of the Qualtrics Survey (i.e. `Qualtrics.SurveyEngine.addOnload()`) this will ensure that things run at the right time and only once.

Use the `AddOnLoad()` for calculating, populating, and storing data that is needed to be done _before_ display, and then use `Qualtrics.SurveyEngine.addOnReady()` for reading data for display. It's a complicated topic, but those two pointers will get you 90% of the way there!
Userlevel 4
Badge +3
Yeah! That is the best place to put it.

And Embedded Data Fields show up in your reporting 🙂
Userlevel 4
Badge +3
I'm glad to hear it!! Congrats!

Leave a Reply