David M. Perlman
David M. Perlman

Reputation: 5090

In Qualtrics surveys, how can you use JavaScript to dynamically set the range of a slider?

I was making a survey in Qualtrics, and needed to have my items show different values of the slider depending on a variable, in my case, the value from a loop and merge. That didn't seem like a thing that you could do with piped text, so I had to figure out how to do it in Javascript.

I'm just posting this as an opportunity to provide the answer I found on my own. As usual with Qualtrics, your mileage may vary, and this may need to be modified for your specific situation. In particular, the question IDs and postTags change depending on whether it is in a loop/merge, and perhaps on other factors.

Upvotes: 2

Views: 1742

Answers (1)

David M. Perlman
David M. Perlman

Reputation: 5090

Put the following code into the javascript section of the question:

// Set the slider range
// First define the function to do it
setSliderRange = function (theQuestionInfo, maxValue) {
    var postTag = theQuestionInfo.postTag
    var QID=theQuestionInfo.QuestionID
    // QID should be like "QID421"
    // but postTag might be something like "5_QID421" sometimes
    // or, it might not exist, so play around a bit.
    var sliderName='CS_' + postTag
    window[sliderName].maxValue=maxValue
    // now do the ticks. first get the number of ticks by counting the table that contains them
    var numTicks = document.getElementsByClassName('LabelDescriptionsContainer')[0].colSpan
        // do the ticks one at a time
        for (var i=1; i<=numTicks; i++) {
        var tickHeader='header~' + QID + '~G' + i
        // the first item of the table contains the minimum value, and also the first tick.
        // so we do some tricks to separate them out in that case.
        var tickSpanArray = $(tickHeader).down("span.TickContainer").children
        var tickSpanArrayLength=tickSpanArray.length
        var lastTickIndex=tickSpanArrayLength - 1
        var currentTickValue = tickSpanArray[lastTickIndex].innerHTML
        currentTickValue=currentTickValue.replace(/^\s+|\s+$/g,'')
        console.log('Tick value ' + i + ' is ' + currentTickValue)
        // now get the new value for the tick
        console.log('maxValue: ' + maxValue + ' numTicks: ' + numTicks + ' i: ' + i)
        var newTickValue = maxValue * i / numTicks //the total number of ticks
        tickSpanArray[lastTickIndex].innerHTML=newTickValue.toString()
        console.log('Changed tick value to ' + newTickValue)
    }
}

var currentQuestionInfo = this.getQuestionInfo()
var currentQuestionID = currentQuestionInfo.QuestionID
// Now call the function
setSliderRange(currentQuestionInfo, theMaxValueYouWant)

If you find my answers helpful, help raise my reputation enough to add "qualtrics" as a valid tag!! Or, if someone else with reputation over 1500 is willing to do it that would be very helpful!

Upvotes: 3

Related Questions