Javascript issue - formatting function not working (for experiment) | XM Community
Skip to main content

Hey guys,

I have been trying to work on javascript for a Qualtrics experiment. 

Basically I am trying to generate a string of numbers and format a particular digit in that string. I run this for 2 minutes, regenerating strings after an answer is subnmitted. This part of the code seems to work fine in the preview. The problem is that it does not do the formatting I indicate. Apart from the shared code, I have also tried using append and split but in both cases the formatting did not work (with my code). I have exhausted most resources and I hope I can get some help here. Thanks a lot! 

I can share the javascript code I have so far (bold is the format function which I think is the issue) - 

 

Qualtrics.SurveyEngine.addOnReady(function()
{

    (irrelevant functions not included)
    var button = document.getElementById('customSubmitButton');
    var input = document.getElementById('id_guess'); 
    var message = document.getElementById('message');

    
// Generate the string 
    
    function generateDigitString(length) {
        let result = '';
        const digits = '0123456789';
        for (let i = 0; i < length; i++) {
            result += digits.charAt(Math.floor(Math.random() * digits.length));
        }
        return result;
    }

    let digitString = document.getElementById('mu_number').textContent;
    let targetDigit =  document.getElementById('target_digit').textContent;

function applyChanges() {
        let styledText = '';
        for (let i = 0; i < digitString.length; i++) {
            console.log(targetDigit);
            if (digitString{i] === targetDigit) {
                console.log('done');
                styledText += '<span style="font-size: 3em">${digitStringli]}</span>';
            } else {
                styledText += '<span style="font-size: 1em">${digitStringi]}</span>';
            }
        }

        document.getElementById('mu_number').innerHTML = styledText;
    }

 

 

I have also tried this - 

function styleTargetDigit(str, targetDigit) {
      const targetStr = targetDigit.toString();
    return str.replace(new RegExp(targetStr, 'g'), '<span style="font-weight:bold;">${targetStr}</span>');
  }

  let styledString = styleTargetDigit(digitString, targetDigit);
  document.getElementById('lambda_number').innerHTML = styledString;
  document.getElementById('target_digit').textContent = targetDigit;
});

 

Be the first to reply!

Leave a Reply