Hide a graphic using Java Script | XM Community
Skip to main content

Hi all,
Apologies for what is no doubt a basic query. I haven't been able to find what I need through searching these forums. I am a complete beginner with Java script so anything I did find was not basic enough for me to understand.
I am seeking assistance with producing java script code that would display a question/graphic based on the selection made in an earlier question.
IF Q7 = 1 OR 2 OR 23 OR 56 OR 209, etc...THEN SHOW THIS QUESTION
Normally I would do this through display logic but the question options are in the hundreds so limits to display logic conditions rule this out.
I would very much appreciate if anyone was able to talk me through the code needed to show/hide a question based on certain recode values.
Many thanks
Chris

You can use the code below. I've added comments to make it easier for you to follow and make changes as required.
Qualtrics.SurveyEngine.addOnload(function () {
    // Hide the question as soon as the page loads
    this.getQuestionContainer().hide();


    //Variable to decide whether to show the question or not. Initially false
    show_answer = false;


    //Create an embedded variable with all the valid choices using a seperator
    // In this a comma "," is used
    var valid_choices = "${e://Field/valid_choices}";
    valid_choices = valid_choices.split(",");


    //Get your entered choice. This is showning an embedded variable
    // Which you can set based on the question type.
    const entered_choice = "${e://Field/entered_choice}";


    // Check if the entered choice is equal to any of the valid choices
    valid_choices.forEach((item) => {
        if (item.trim() == entered_choice) {
            show_answer = true;
        }
    });


    //Show the question, if the condition is met
    if (show_answer == true) {
        this.getQuestionContainer().show();
    }


    //Optionally you can add a condition to click the next button
    // If you only have that one question on the page
    if (show_answer == false) {
        this.clickNextButton();
    }
});


Hide_Show_Question__JS.qsfChrisF Please find attached the qsf with JavaScript applied on Q1 and based on Q1 response selected choice we set the "embedded data". You can use the embedded data to apply display logic (see Q2 in attached qsf). This approach will work even if following question (Q2) might have kept mandatory...
In attached qsf (survey) Q2 is asked if user select 1,2,3 or 4... you can modify it as per your requirement. Please look the JS code in Q1.


Thank you very much ahmedA, this has worked a treat! Really appreciate your response and how well laid out it was for a novice such as myself.
Mohammedali_Rajapakar_Ugam , thanks for taking the time to provide a reply and the template file. Very much appreciated.


Leave a Reply