Is there a way to set global variables or have custom question Javascript only run once? | XM Community
Skip to main content

Basically we have custom javascript on the first question of our survey and we only want it to run the first time the user sees the question. If the user advances in the survey and then goes back to that question, we do not want to have the code run again. I think this could be solved with a global counter variable that is used throughout the survey, but I'm not if/how to set such a variable. I tried setting a variable in the code we use for the question but as expected when the user goes back to the question, the code runs again and resets the variable so the counter doesn't work. Thanks.

Hi jkunzel ,
Make a "flag" -named embedded data variable and make sure it is defined before that question block or better at the top .

and then use the code below to run the function just once using the following technique:

Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
if(parseInt('${e://Field/flag}')==0)


console.log("run only once");//Replace it with you code that needs to be run only once



 Qualtrics.SurveyEngine.setEmbeddedData("flag", 1);


}
else
{console.log("is not runinng again");  
console.log(parseInt('${e://Field/flag}'));
}


});

Qualtrics.SurveyEngine.addOnReady(function()
{

/*Place your JavaScript here to run when the page is fully displayed*/


});

Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/

});

Hope it resolves your query😊!!


Thank you! This is exactly what I needed :)


Leave a Reply