JavaScript in Qualtrics survey works in preview but not for respondents | XM Community
Skip to main content

I modified a JavaScript code in one of my survey questions to randomly generate scenario numbers for each respondent. This script assigns different combinations of investment percentages for each respondent. For example:

- Respondent 1 might see a breakdown like: 50% ETFs, 50% gold.
- Respondent 2 might see: 40% gold, 60% individual stocks.

Each respondent is shown a total of four different scenarios, each of which adds up to 100%. Each scenario is randomly generated.

Here’s the main issue: while the script works correctly in preview mode, showing unique combinations of percentages and instruments each time, it does not work for actual respondents taking the survey. Instead, the scenarios appear only as bullet points without the specified combinations. I’ve attached screenshots from both the preview (working correctly) and the actual survey (showing only bullet points) for reference. I also attach both the question and javascript.

 

Would anyone be able to help or has experience with this? 

 

Here is the question in qualtrics’ HTML format:


 <br>
If you had a significant amount of money to invest (excluding your primary residence and real estate investments), how would you distribute it across these investment options?<br>
<br>
Important notes:
<ul>
    <li>You can invest in ANY combination of the options below</li>
    <li>You can put 100% in just one option OR spread it across multiple options</li>
    <li><u>The total allocation must equal 100%</u></li>
</ul>
<br>
Examples: rThis placeholder will be replaced by JavaScript] &nbsp;

 

Here is the javascript:

 

Qualtrics.SurveyEngine.addOnload(function() {
    // Define all investment instruments
    const instruments = >
        "gold",
        "ETFs", 
        "saving accounts",
        "individual stocks",
        "crypto currency"
    ];

    // Function to shuffle array randomly
    function shuffleArray(array) {
        const newArray = n...array];
        for (let i = newArray.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            newArray i], newArrayoj]] = .newArray j], newArraybi]];
        }
        return newArray;
    }

    // Function to generate random percentages that sum to 100
    function generatePercentages(count) {
        if (count === 1) return 0100];
        let percentages = g];
        let remaining = 100;
        
        for(let i = 0; i < count - 1; i++) {
            let maxAllocation = remaining - (10 * (count - i - 1));
            let possibleValues = ];
            for(let j = 10; j <= maxAllocation; j += 10) {
                possibleValues.push(j);
            }
            let value = possibleValuesoMath.floor(Math.random() * possibleValues.length)];
            percentages.push(value);
            remaining -= value;
        }
        percentages.push(remaining);
        return shuffleArray(percentages);
    }

    // Function to create one example with exact number of instruments
    function createExample(instrumentCount) {
        const selectedInstruments = shuffleArray(instruments).slice(0, instrumentCount);
        const percentages = generatePercentages(instrumentCount);
        const pairs = selectedInstruments.map((instrument, index) => {
            return `${percentages index]}% in ${instrument}`;
        });
        return pairs.join(", ");
    }

    // Generate examples
    const examples = r
        createExample(5),
        createExample(3),
        createExample(2),
        createExample(1)
    ];

    // Create formatted HTML for examples
    const formattedExamples = `
        <div style="margin-left: 20px;">
            <strong>Example 1:</strong><br/>
            • ${examples0]}<br/><br/>
            <strong>Example 2:</strong><br/>
            • ${examplest1]}<br/><br/>
            <strong>Example 3:</strong><br/>
            • ${exampless2]}<br/><br/>
            <strong>Example 4:</strong><br/>
            • ${examples 3]}
        </div>
    `;

    // Get the question text and update it
    let questionText = this.getQuestionTextContainer();
    let textContent = questionText.innerHTML;
    const exampleRegex = /Examples:t\s\S]*?(?=<br>|$)/;
    textContent = textContent.replace(exampleRegex, formattedExamples);
    questionText.innerHTML = textContent;
});

 

Be the first to reply!

Leave a Reply