Hi all, I’m trying to calculate recode values in Qualtrics using JavaScript. I want to count all the recode values and if the count is greater than or equal to 17, then take the sum of those recodes. Otherwise, I want return “N/A” as the risk score. Below is what I have so far, but my output keeps returning “N/A” regardless if an actual score should be calculated. Any ideas why?
Qualtrics.SurveyEngine.addOnload(function() {
// Get the recode values from the previous questions
var recodeValues = [
parseInt("${q://QID9/SelectedChoicesRecode}", 10),
parseInt("${q://QID10/SelectedChoicesRecode}", 10),
parseInt("${q://QID11/SelectedChoicesRecode}", 10),
parseInt("${q://QID12/SelectedChoicesRecode}", 10),
parseInt("${q://QID14/SelectedChoicesRecode}", 10),
parseInt("${q://QID15/SelectedChoicesRecode}", 10),
parseInt("${q://QID16/SelectedChoicesRecode}", 10),
parseInt("${q://QID17/SelectedChoicesRecode}", 10),
parseInt("${q://QID18/SelectedChoicesRecode}", 10),
parseInt("${q://QID19/SelectedChoicesRecode}", 10),
parseInt("${q://QID20/SelectedChoicesRecode}", 10),
parseInt("${q://QID23/SelectedChoicesRecode}", 10),
parseInt("${q://QID24/SelectedChoicesRecode}", 10),
parseInt("${q://QID25/SelectedChoicesRecode}", 10),
parseInt("${q://QID26/SelectedChoicesRecode}", 10),
parseInt("${q://QID27/SelectedChoicesRecode}", 10),
parseInt("${q://QID28/SelectedChoicesRecode}", 10),
parseInt("${q://QID29/SelectedChoicesRecode}", 10),
parseInt("${q://QID30/SelectedChoicesRecode}", 10)
];
// Log the raw recode values
console.log("Recode Values: ", recodeValues);
// Filter out any invalid values (e.g., unanswered questions)
var validValues = recodeValues.filter(function(value) {
console.log("Checking value:", value, "Is valid (not NaN):", !isNaN(value));
return !isNaN(value); // Filter only valid numbers
});
// Log the valid recode values after filtering
console.log("Valid Values: ", validValues);
// Check if the count of valid recode values is >= 17
if (validValues.length >= 17) {
// Sum the recode values
var sum = validValues.reduce(function(acc, current) {
console.log("Adding value:", current, "Current sum:", acc);
return acc + current;
}, 0);
// Log the calculated sum
console.log("Final Risk Score (sum):", sum);
// Set the Risk Score in an embedded data field
Qualtrics.SurveyEngine.setEmbeddedData("RiskScore", sum);
// Optionally display the result on the page
document.getElementById("riskScoreDisplay").innerHTML = "Risk Score: " + sum;
} else {
// Log that the condition for valid values was not met
console.log("Less than 17 valid values. Returning 'N/A'");
// If less than 17 valid values, return "N/A"
Qualtrics.SurveyEngine.setEmbeddedData("RiskScore", "N/A");
// Optionally display the N/A result
document.getElementById("riskScoreDisplay").innerHTML = "Risk Score: N/A";
}
});
And this is what I have for the HTML view for the question:
Risk Score: <div id="riskScoreDisplay"></div>