Using javascript and loop-and-merge to populate a choice in a multiple choice question | XM Community
Skip to main content
I have a two-alternative multiple choice question whose alternatives are labelled "1" and "2".

I'd like to use a loop-and-merge field that contains values 1 and 2 to determine whether "1" is chosen or "2" is chosen when the question is displayed.

However, the code below throws an "unexpected {" error:

Qualtrics.SurveyEngine.addOnload(function()

{

var questionId = this.questionId;

questionID.setChoiceValue(${lm://Field/9}, true);



});



And even this code (where I've simply tried to get "1" to be chosen) doesn't work:

Qualtrics.SurveyEngine.addOnload(function()

{

var questionId = this.questionId;

questionID.setChoiceValue(1, true);



});



I'd be grateful for any help on this.

--Cheers, Mike
@MikeSmi,



JavaScript variables are case sensitive so questionID is undefined which is what is causing the error. However, even if the variable name were correct your code is still wrong. In an addOnload function `this` is the question object so you want:

```

Qualtrics.SurveyEngine.addOnload(function()

{

this.setChoiceValue(${lm://Field/9}, true);

});

```
Thanks, TomG, but the code you've provided still throws this error when I try to save it:



Invalid JavaScript! You cannot save until you fix all errors: Unexpected token {
Ah, got it now. I needed to encompass the variable name in quotes: "${lm://Field/9}".

The code works fine now-- Thanks again!

Leave a Reply