Help Calculating Recode Values | XM Community
Skip to main content

Hello, I am trying to create a question to calculate a “Risk Score” based on answers to previous questions.

The previous questions contain recode values that are already in Qualtrics. Here is the intended calculation for Risk Score: If the count of the recode values is >= 17, then take the sum of the recode values. Otherwise, return “N/A” to the user. If anyone could provide any guidance as I am not proficient in Java Script, that would be greatly appreciated!

@sam.s77 Hi Sam! here is how you can do it. If you like my answer marking it as a best answer would be nice :)

  1. Set recode values, go to the survey question, click on the answer choices, and enable Recode Values under Advanced Question Options. These recode values will be used to calculate the risk score.
  2. Create an Embedded Data Field. Go to Survey Flow. Add a New Element and select Embedded Data. Create an embedded data field (e.g., RiskScore). This will store the final result (either the sum or “N/A”).

  3. Embed JavaScript on load. Navigate to the question after your recoded questions. Click on Advanced Question Options (gear icon) and choose Add JavaScript

    Here is the code example:
     

    Qualtrics.SurveyEngine.addOnload(function() {
    // Get the recode values from the previous questions
    var recodeValues = e
    parseInt("${q://QID1/ChoiceNumericEntryValue}", 10), // Replace QID1 with your actual Question ID
    parseInt("${q://QID2/ChoiceNumericEntryValue}", 10), // Replace QID2 with your actual Question ID
    // Add more questions as needed
    ];

    // Filter out any invalid values (e.g., unanswered questions)
    var validValues = recodeValues.filter(function(value) {
    return !isNaN(value); // Filter only valid numbers
    });

    // 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) {
    return acc + current;
    }, 0);

    // 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 {
    // 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";
    }
    });

     

  4. When you do this `Qualtrics.SurveyEngine.setEmbeddedData("RiskScore", sum);` it means that RiskScore will be stored as part of the response data when the respondent submits their survey.

    After that you may use “RiskScore” variable both for displaying and next page logic :)


@artem.alekhin For step two when looking at the survey flow, this is what I have. After I add the Java Script and preview the survey the risk score comes out blank, meaning it did not calculate anything. In the survey building do I need to need to include any piped text for the calculation to appear?

 


@sam.s77 
For Step 2 let me clarify:
You need to ensure that RiskScore is part of your Survey Flow:

1. Go to the Survey Flow section in your survey.

2. Add an Embedded Data block at the start of the flow (or wherever appropriate).

3. In the Embedded Data block, add a new field called RiskScore.

It should look something like this:

Embedded Data
RiskScore = (leave blank)


--------
The code part “document.getElementById("riskScoreDisplay").innerHTML = "Risk Score: " + sum;” wouldn’t work until you add html element. This html element should be added on the same question where javascript is executed. 

<div id="riskScoreDisplay"></div>

-----
You should use ${q://QID31/ChoiceNumericEntryValue} (or a similar piped text format based on the question type) to pull the numeric value associated with the respondent’s answer, not the question text.

Fix: In the Survey Flow, update the embedded data field to capture the choice numeric value (or whatever value you are trying to sum). For example:

RiskScore = ${q://QID31/ChoiceNumericEntryValue}

​​​​​​​

Steps:

1. Find the Correct Piped Text:

• Go to the survey editor, click on the question with the recode values, and find the correct piped text for the answer values (it will be under Insert Piped Text > Selected Choice > Recode Value or Numeric Entry Value depending on the question type).

2. Set RiskScore with Recode Values:

• Update the RiskScore embedded data field with the correct piped text that represents the recoded values of the answers.


@artem.alekhin I’m still unsure what you mean by “click on the question with the recode values, and find the correct piped text for the answer values” because the RiskScore is calculating a score based on recode values from a variety of questions. 

 

I added this as a HDML element to the question with the Java Script to calculate the RiskScore. However, the RiskScore is always returning “N/A” even when a total should be calculated. I am unsure what I should be added for the piped text in order for the summed value for RiskScore to work.

 


@sam.s77 When I mentioned “correct piped text,” I meant ensuring that you’re referencing the correct questions and their respective answer values (e.g., Recode Values or Numeric Entry Values) when creating your recodeValues array.

 

If you’re consistently seeing “N/A,” this indicates that the logic is always triggering the else condition, which means something is off in the filtering or calculation process. Here’s how you can debug the issue:

Steps to Debug:

1. Check the Filter Logic:

• Ensure the filter is correctly identifying valid recode values. To help with this, you can add some console.log() statements inside your JavaScript code to see what values are being processed.

2. Add Debugging Logs:

In your JavaScript code, log the following to the console:

console.log("Valid Values: ", validValues); // Logs filtered recode values
console.log("Original Recode Values: ", recodeValues); // Logs the original recode values
console.log("isNaN check: ", !isNaN(value)); // Logs the result of the isNaN check

This will help you understand if:

• The validValues array is getting the correct, filtered recode values.

• The recodeValues array is being populated properly.

• Whether the isNaN() function is correctly filtering out invalid values.

3. Inspect the Console Output:

• Use Chrome DevTools (or any browser inspector) to check the console output.

1. Preview your survey in Google Chrome.

2. Right-click on the page and select Inspect.

3. Go to the Console tab to view the logs.

• Review the logged values for validValues and recodeValues to see if they match what you expect. If validValues is empty or incorrect, that’s where the issue lies.

4. Check for Errors in the Console:

• If there are any JavaScript errors, they will appear in the console as well. If there’s an issue in your script preventing it from executing correctly, the error message will point to the specific line in your code that needs attention.

5. Review Your Logic:

• If the logs show that validValues is empty or incorrect, revisit your filter logic. You can try:

validValues = recodeValues.filter(function(value) {
console.log("Value: ", value, "isNaN: ", isNaN(value)); // Debugging each value
return !isNaN(value);
});

• This will help ensure the filter is working as intended and not excluding valid values.

 

Following these steps should help you pinpoint the issue. Let me know if you need more details or if something is unclear!

Here is a code example from pervious message with debugging logs. Please see at what point the script behaves incorrectly in inspector:

Qualtrics.SurveyEngine.addOnload(function() {
// Get the recode values from the previous questions
var recodeValues =
parseInt("${q://QID1/ChoiceNumericEntryValue}", 10), // Replace QID1 with your actual Question ID
parseInt("${q://QID2/ChoiceNumericEntryValue}", 10), // Replace QID2 with your actual Question ID
// Add more questions as needed
];

// 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";
}
});


 


Leave a Reply