How does qualtrics give value to a sequence of variable in a loop? | XM Community
Skip to main content
Hi, I would like to give values to a sequence of global variable in qualtrics. To illustrate, I have set var1, var2, var3 in the survey flow. and I have define data=['apple', 'banana', 'orange'] in the javascript. I am using the following script. Qualtrics.SurveyEngine.setEmbeddedData('var1', data[0]); Qualtrics.SurveyEngine.setEmbeddedData('var2', data[1]); Qualtrics.SurveyEngine.setEmbeddedData('var3', data[2]); Is there a way to do it in a loop? For example, I am thinking for (i = 0; i < rd_option1.length; i++) { Qualtrics.SurveyEngine.setEmbeddedData('var+i', data[i]); } But it seems like qualtrics does not read 'var+i' properly in a loop? Is there a way to solve it? Thank you very much!
Hi @Rui , You're almost there, just remove the quotes around var+i ```javascript Qualtrics.SurveyEngine.setEmbeddedData(var+i, data[i]); ``` Please give it a try and let us know if it works, thanks. Zhen
@Zhen Thank you for your reply. Unfortunately, it does not work. The code does not assign value from data[i] to vari. Does it work for you?
It should be: ``` for (i = 0; i < data.length; i++) { Qualtrics.SurveyEngine.setEmbeddedData("var"+(i+1), data[i]); } ```
@TomG Thanks for your answer. Please let me take the chance to ask for something general. e.g. I want to define var11,var12,var21,var22 with data1, data2, how should I define the variable in the loop? I tried the following: for (j = 1; j<4; i++) { for (i = 0; i < data.length; i++) { Qualtrics.SurveyEngine.setEmbeddedData("var"+j+(i+1), data+j[i]); } } but it is returning error. Would you have a good idea?
> @Rui said: > @TomG Thanks for your answer. Please let me take the chance to ask for something general. e.g. I want to define var11,var12,var21,var22 with data1, data2, how should I define the variable in the loop? I tried the following: > > for (j = 1; j<4; i++) { > for (i = 0; i < data.length; i++) { > Qualtrics.SurveyEngine.setEmbeddedData("var"+j+(i+1), data+j[i]); > } > } > > but it is returning error. Would you have a good idea? I'm not sure what you are trying to do. Are data1 and data2 arrays? Anyway, in your j for loop you have to increment j not i. If data1 and data2 are arrays, then data+j[i] is the wrong syntax.