Dear All,
I want participants to be able to generate a random value (0-10) multiple times on the same stage. They can do this by cklicking a button. I would like to track (i.e. store in the decisions table)
I use the following code.
let timesClicked = parseInt(localStorage.getItem("timesClicked"));
function genvalue() {
timesClicked++;
let randomval= Math.floor(Math.random() * 11);
let randomValKey = `randomval${timesClicked}`;
localStorage.setItem('randomValKey', randomval);
localStorage.setItem("timesClicked", timesClicked);
setValue('timesClicked',timesClicked);
record('randomValKey', randomval);
console.log(`Stored ${randomval} in ${randomValKey}`);
console.log(`Button clicked ${timesClicked} times`);
}
Locally, the dynamic key works fine , but I fail to store a new variable (randomval1, randomval2, etc.) in the database each time the button is clicked. What happens is that one single variable called "randomValKey" is created once, and then updated with each button click.
Can anyone advise how to change the line
record('randomValKey', randomval);
such that the value of "randomValKey" is used to create a new variable (rather than using the literal string 'randomValKey' in the record function)?.
Any suggestion will be much appreciated, thanks a lot in advance!
Best, Philipp
Hi Philipp,
record() does not work within a function. This because having this in a loop is sensitive to exploding the number of variables and clogging the development server.
You can take record() outside the function and use setValue within it.
If you have a dynamic number of values, you might consider storing the generated values in a JS element, e.g. a vector, and write this vector as a comma separated string to the database when the participant leaves the page by clicking the ‘Continue’ button.
Cheers, Lucas