Javascript to use previous multiple choice responses to display text on a new question | XM Community
Solved

Javascript to use previous multiple choice responses to display text on a new question

  • 13 May 2022
  • 2 replies
  • 492 views

Badge +1

I have two multiple choice questions asking about respondents' own perceived ranking in groups, let's call them group1 and group2. Both questions allow for responses from 1 to 10. I'd like to use the responses from these to questions to see if they're better, worse, or the same based on their responses to these two questions. As an example, if a respondent chooses a ranking of 7 in group1 and 4 for group2, a third question will point out that their perceived ranking is lower in group2 than it is in group1. Here's my setup so far:
Embedded data at top of survey flow:
Screen Shot 2022-05-13 at 11.34.28 AM.pngThe third question, where I'd like to show the respondent their difference in ranking, better, worse, or same:
Screen Shot 2022-05-13 at 11.38.02 AM.pngAnd my javascript associated with the third question:
Qualtrics.SurveyEngine.addOnload(function()
{
    /*Place your JavaScript here to run when the page loads*/
    
    var group1 = parseInt("${q://QID21/ChoiceGroup/SelectedChoices}");
    var group2 = parseInt("${q://QID22/ChoiceGroup/SelectedChoices}");
    var result;
    
    if (group1 > group2) { result = "better";} else if (group1 < group2) { result = "worse";} else { result = "same";}
    
    Qualtrics.SurveyEngine.setEmbeddedData("result",result);
});
The result is that I only get 'null' where I'm expecting better / worse / same to show up.
New to javascript so any pointers would be greatly appreciated. Thanks!

icon

Best answer by bgooldfed 16 May 2022, 07:28

View original

2 replies

Userlevel 5
Badge +25

Hi wwf!
Your code actually works fine (well done!), it's the behaviour of Qualtrics that is causing your issue.
Qualtrics loads in piped text before your code runs on page load, so it won't pipe in the updated value. The easiest solution would be to add a line to the end of your code block which updates the text on the page with your updated result.
jQuery example:
jQuery("#"+this.questionId+" .QuestionText").text("Result is: " + result);
Alternatively you could set the embedded data field in a previous question block, if you have other questions in between the multiple choice and the result blocks.

Badge +1

Thank you, bgooldfed!! Adding your jquery line works perfectly!

Leave a Reply