Hi, I have calculations in my JavaScript code not working when the first time I visit the page. But when I revisit the page by hitting “Back” or “Next” and coming back to the page, the calculations results will appear. I attached two screenshots, one is what it looks like when I visit the page first time, one is what it looks like when I revisit the page. Could someone help me figure out the potential issues and solutions? Thank you so much!
Here is my interface:
Round 1 Feedback
Investment return this round: ${e://Field/investment_return_this_round}
Investment return based on your own strategy this round: ${e://Field/investment_return_own_strategy}
Investment return based on AI-suggested strategy this round: ${e://Field/investment_return_ai_strategy}
Here is my JavaScript:
Qualtrics.SurveyEngine.addOnload(function() {
// Retrieve input values for Decision1, Decision2_1, and Decision2_2
var decision1 = parseFloat("${q://QID1453/ChoiceTextEntryValue}");
var decision2_1 = parseFloat("${q://QID1492/ChoiceTextEntryValue/5}");
var decision2_2 = parseFloat("${q://QID1492/ChoiceTextEntryValue/6}");
// Initialize variables for investment returns
var investmentReturnThisRound, investmentReturnOwnStrategy, investmentReturnAIStrategy;
// Calculate "Investment return this round" with conditional logic
if (decision1 === 100) {
investmentReturnThisRound = round(
decision1 * 0.8306 * 0 +
decision1 * 1.0028 * 1,
2
) + "%";
} else if (!isNaN(decision1) && !isNaN(decision2_1) && !isNaN(decision2_2)) {
investmentReturnThisRound = round(
decision1 * 0.8306 * 0 +
decision1 * 1.0028 * 1 +
(decision2_1 * 0.8306) +
(decision2_2 * 1.0028),
2
) + "%";
} else {
investmentReturnThisRound = "Invalid Input"; // Handle invalid cases
}
// Calculate "Investment return based on your own strategy this round"
if (decision1 === 100) {
investmentReturnOwnStrategy = "N/A"; // Show "N/A" when decision1 equals 100
} else if (!isNaN(decision1) && !isNaN(decision2_1) && !isNaN(decision2_2)) {
investmentReturnOwnStrategy = round(
100 * ((decision2_1 / (100 - decision1)) * 0.8306) +
100 * ((decision2_2 / (100 - decision1)) * 1.0028),
2
) + "%";
} else {
investmentReturnOwnStrategy = "Invalid Input"; // Handle invalid cases
}
// Calculate "Investment return based on AI-suggested strategy"
investmentReturnAIStrategy = round(
(0.8306 * 0 * 100) + (1.0028 * 1 * 100),
2
) + "%";
// Set Embedded Data for displaying values in the survey
Qualtrics.SurveyEngine.setEmbeddedData("investment_return_this_round", investmentReturnThisRound);
Qualtrics.SurveyEngine.setEmbeddedData("investment_return_own_strategy", investmentReturnOwnStrategy);
Qualtrics.SurveyEngine.setEmbeddedData("investment_return_ai_strategy", investmentReturnAIStrategy);
// Helper function for rounding numbers
function round(value, decimals) {
return Number(Math.round(value + "e" + decimals) + "e-" + decimals);
}
});