Java scrip works in Question preview but not Survey Preview | XM Community
Skip to main content
Question

Java scrip works in Question preview but not Survey Preview

  • February 19, 2025
  • 0 replies
  • 17 views

VinceBirdy
Forum|alt.badge.img

 

Java scrip about counting character works in Question preview.  But not Survey Preview.

Here is the Java script I am using for counting characters remaining in the multiple question type with text entry box: 

 

Qualtrics.SurveyEngine.addOnReady(function() {
    // Get the text entry box
    const textEntryBox = this.questionContainer.querySelector('textarea');

    // Set the character limit (change this to match your question's limit)
    const charLimit = 100;

    // Create a span element to display the countdown
    const countdownSpan = document.createElement('span');
    countdownSpan.style.marginLeft = '10px';
    countdownSpan.style.fontSize = '0.9em';
    countdownSpan.style.color = '#888';
    textEntryBox.parentNode.insertBefore(countdownSpan, textEntryBox.nextSibling);

    // Function to update the countdown
    function updateCountdown() {
        const remainingChars = charLimit - textEntryBox.value.length;
        let reminderText = '';

        // Get the survey language
        const surveyLanguage = Qualtrics.SurveyEngine.getEmbeddedData('Q_Language');

        // Set reminder text based on survey language
        if (surveyLanguage === 'JA') {
            reminderText = `残り文字数: ${remainingChars}`;
        } else if (surveyLanguage === 'en') {
            reminderText = `Characters remaining: ${remainingChars}`;
        } else {
            reminderText = `Characters remaining: ${remainingChars}`; // Default
        }

        countdownSpan.textContent = reminderText;

        // Change color if the limit is exceeded
        if (remainingChars < 0) {
            countdownSpan.style.color = 'red';
        } else {
            countdownSpan.style.color = '#888';
        }
    }

    // Add event listener to update countdown as the user types
    textEntryBox.addEventListener('input', updateCountdown);

    // Initialize the countdown on page load
    updateCountdown();
});

 

Also, why the text entry box becomes smaller when I switch the language? Can I be fixed size as width as the option bar? 

 

Also, may I know I also would like to add the character limit valediction on above function, what should I add? For example, if over 100 characters, the survey should stop the respondent continue the survey with reminder “you have exceeded 100 characters limit, please edit your answer.” in selected English language. In Japanese, it will show ‘100 文字の制限を超えています。回答を編集してください。’ 

 

Thank you so much !

0 replies

Be the first to reply!

Leave a Reply