Search code examples
javascriptqualtrics

Individual custom start position in Qualtrics through Javascript


I want to use either a slider question or a draggable bar chart in Qualtrics to present to respondents how they answered in former questions. More specifically, I compute a value out of then answers with weighting, and want the slider or bar to be positioned at this value. Notably, as each respondent has a value (stored in an embedded data field), the position will thereby be individual for each respondent. Piping only works for text fields, as far as I understood the support page.

Based on this question/answer I came to the following code for the bar graph:

Qualtrics.SurveyEngine.addOnload(function()
{
   var result = "${q://Field/result}";
   var qwidth = $('QID1936~1~track').offsetWidth;
   var resrec = ((qwidth*result)/100);
   $('QID1936').select('.bar').each(function(name, index) {
            name.setStyle({ width: resrec +"px"});
   });
});

Basically, I get the result for each respondent out of the embedded data, get the width of the full bar graph, compute the ratio that should be colored based on the result, and update the position of the bar graph (following the mentioned answer).

Funny enough, everything works when done in the console. Also, the embedded data is correctly loaded, qwidth as well. Two problems arise: it seems resrec could be computed wrongly, as a console.log() spits out 0 instead of the correct value. I assumed this could be somehow as a variable is not recognized as number, but several tries with Number() or 0+var did not change how this works in Qualtrics. In the console, it works just fine. Also, no update of the bar (or slider with similar code) happens, neither with the correct value nor with the 0 that is produced by Qualtrics.

I search for two things: either a solution to the Javascript problem as described, basically how I can update the bar or slider with embedded data. Or another solution how to directly get embedded data into one of those two question formats as a starting value for each respondent individually.

Thanks for your help or ideas!


Solution

  • Try this:

    Qualtrics.SurveyEngine.addOnload(function()
    {
        var qid = this.questionId;
        var result = parseFloat("${e://Field/result}");
        var qwidth = $(qid+'~1~track').offsetWidth;
        var resrec = ((qwidth*result)/100);
        $(qid).select('.bar').each(function(name, index) {
            name.style.width = resrec + "px";
        });
    });
    

    Notes:

    1. It is best not to use a hardcoded QID
    2. In a pipe use e: to refer to an embedded variable. q: is for questions.
    3. Use parseFloat to convert the string to a number
    4. No need to use setStyle if you are only setting one value