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 (targetDigit) 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 hope I can get some help here. Thanks a lot!
I believe it is because the whole string is treated as 1 character instead of a collection of numbers. I also tried split function but for some reason it still did not work.
I can share the javascript code I have so far (applychanges() is the format function which I think is the issue). I have also tried running the last code segment separately –
Code-
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">${digitString[i]}</span>';
} else {
styledText += '<span style="font-size: 1em">${digitString[i]}</span>';
}
}
document.getElementById('mu_number').innerHTML = styledText;
applyChanges()
}
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;
});
Apoorv Kanoongo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.