Is there a way to modify the output to show the order of a JS randomization within a question? | XM Community

Is there a way to modify the output to show the order of a JS randomization within a question?

  • 17 November 2022
  • 2 replies
  • 36 views

Badge

I have a survey that randomizes the order of two photos within a question using javascript. The photo sources for each question are pulled from a single row in a loop and merge that is randomized. Participants then answer a single multiple choice question about the two photos. Currently, the csv output only gives the participant response to the each question. I would also like it to give the order in which the photos were presented. Any thoughts how to go about this? I've been messing with embedded data with no success. Also looking into SQL
Here is my randomization in JS: (My two photos are after

    in html)
    function htmlShuffle(elem) {
      function shuffle(arr) {
        var len = arr.length;
        var d = len;
        var array = [];
        var k, i;
        for (i = 0; i < d; i++) {
          k = Math.floor(Math.random() * len);
          array.push(arr[k]);
          arr.splice(k, 1);
          len = arr.length;
        }
        for (i = 0; i < d; i++) {
          arr[i] = array[i];
        }
        return arr;
      }
      var el = document.querySelectorAll(elem + " *");
      document.querySelector(elem).innerHTML = "";
      let pos = [];
      for (let i = 0; i < el.length; i++) {
        pos.push(i);
      }
      pos = shuffle(pos);
      for (let i = 0; i < pos.length; i++) {
        document.querySelector(elem).appendChild(el[pos[i]]);
      }
    }
    htmlShuffle("ul");


2 replies

Userlevel 5
Badge +25

Hi Eme,
You could store the order in a single embedded field. Rather than copy+paste your entire function I've just put some notes below on where to try adding in some extra lines.
//--- put this outside of your function ---
//create an empty variable to store the order
var order;

//--- ---


//--- add this to your function in the appropriate place ---
//...

pos = shuffle(pos);

//add the shuffled position to the order array
order.push(pos,",");
//set the order embedded field to the current order array
Qualtrics.SurveyEngine.setEmbeddedData('order', order);

for (let i = 0; i < pos.length; i++) {
    document.querySelector(elem).appendChild(el[pos[i]]);
}
//... continue function as normal
This should store each shuffled position in an embedded field, separated by a comma.
Good luck!

Badge

Huge thanks bgooldfed!

Leave a Reply