Calculate mean with Javascript and embedded data. | XM Community
Skip to main content

I want to divide my participants into two groups based on their scores on 10 statements on a 10-Point Likert scale. Consequently, I have created two branches to evenly divide the one group (with mean of 0 to 5) and the other group (with mean of 5.01 to 10). 

I created an embedded data field in my survey flow (also already tried with the data codes in one block):

 

And added this code to de Javascript of the matrix: 

Qualtrics.SurveyEngine.addOnPageSubmit(function(type) {
    // Retrieve values from embedded data fields and parse them as floats
    var selAnsw1 = parseFloat("${e://Field/SelAnsw1}");
    var selAnsw2 = parseFloat("${e://Field/SelAnsw2}");
    var selAnsw3 = parseFloat("${e://Field/SelAnsw3}");
    var selAnsw4 = parseFloat("${e://Field/SelAnsw4}");
    var selAnsw5 = parseFloat("${e://Field/SelAnsw5}");
    var selAnsw6 = parseFloat("${e://Field/SelAnsw6}");
    var selAnsw7 = parseFloat("${e://Field/SelAnsw7}");
    var selAnsw8 = parseFloat("${e://Field/SelAnsw8}");
    var selAnsw9 = parseFloat("${e://Field/SelAnsw9}");
    var selAnsw10 = parseFloat("${e://Field/SelAnsw10}");

    console.log("SelAnsw1: " + selAnsw1);
    console.log("SelAnsw2: " + selAnsw2);
    console.log("SelAnsw3: " + selAnsw3);
    console.log("SelAnsw4: " + selAnsw4);
    console.log("SelAnsw5: " + selAnsw5);
    console.log("SelAnsw6: " + selAnsw6);
    console.log("SelAnsw7: " + selAnsw7);
    console.log("SelAnsw8: " + selAnsw8);
    console.log("SelAnsw9: " + selAnsw9);
    console.log("SelAnsw10: " + selAnsw10);

    // Calculate the sum of the answers
    var sum = selAnsw1 + selAnsw2 + selAnsw3 + selAnsw4 + selAnsw5 + selAnsw6 + selAnsw7 + selAnsw8 + selAnsw9 + selAnsw10;

    // Calculate the mean score
    var meanScore = sum / 10;

    // Log the values for debugging purposes
    console.log("Sum: " + sum);
    console.log("Mean Score: " + meanScore);

    // Set the Embedded Data field with the calculated mean score
    Qualtrics.SurveyEngine.setEmbeddedData("MeanScore", meanScore.toFixed(2));  // Optionally round to 2 decimal places
});
 

However, when I test my survey and get my output to SPSS, the meanScore is not calculated, but just fills out the code. For example: “(3 + 6 + 8 + 10 + 5 + 8 + 2 + 7 + 1 + 5) / 10” instead of actually calculating the mean.

 

Does anyone know what the problem is?

hi @charjg18 Instead of Javascript you can do the same thing using Math Operations. See below image for a similar setup.

Based on the calculated mean value, question blocks can be displayed accordingly.

 


Leave a Reply