Populating multiple choice options from a string | XM Community
Skip to main content

I have a dataset that I have imported as a contact list into my survey. There is a string variable called “tool_list”, which is a comma separated list of tools for each recipient of the survey. For example, the value of tool_list could be “tool A, tool B, tool C, tool D” or “tool A, tool E”, etc. I want to use custom javascript to split the string, and then create multiple choice options for a question based on the new strings. 

For example, if a person had the tool_list “tool A, tool B, tool X, tool Z”, I want them to see a survey question with the multiple choice options a) tool A b) tool B c) tool X d) tool Z. They should be able to select as many options as they would like to. 

One thing that complicates this task is that the length of the lists varies person to person. 

Thank you for any comments or ideas!! :) 

Hi @blairmoore ,

Qualtrics.SurveyEngine.addOnload(function() {
    // Get the value of the "tool_list" variable for the current respondent
    var toolList = "${e://Field/tool_list}";

    // Split the tool list string into individual tools
    var tools = toolList.split(", ");

    // Get the multiple choice question element
    var mcQuestion = this.getQuestionContainer();

    // Loop through each tool and dynamically add it as an option to the multiple choice question
    for (var i = 0; i < tools.length; i++) {
        var tool = toolsi].trim(); // Remove leading and trailing whitespace
        mcQuestion.querySelector('.QuestionStructure').innerHTML += '<label class="Choice">' +
            '<input type="checkbox" name="toolOption" value="' + tool + '">' +
            '<span>' + tool + '</span>' +
            '</label>';
    }
});
 

This code will dynamically generate checkbox options for each tool in the "tool_list" variable. It assumes that the "tool_list" variable is stored as an embedded data field and is accessible using "${e://Field/tool_list}".


Hi @Umang Upadhyay thank you for your response!

I added this code to the javascript editor. Just a few questions, as I am an absolute beginner in JS and html. When I compiled the survey and tested it out, the results of this code didn’t show up. Do I need to add something to the html of the question? 

Second, when I am creating the question that should be filled in by the javascript code, does it matter how many choices I manually create? The default is set to 3. And should I be changing the placeholder text from “Click to write Choice 1”? 

Thank you! This is so helpful. 


Hello, I have encountered a similar issue and the above answer does not work for me. Have you solved this problem? Any insight will be appreciated!


Leave a Reply