Search code examples
javascriptqualtrics

Using Javascript with embedded Qualtrics variables


I am using Qualtrics to collect data on an experiment related to behavioral economics.

I need to provide respondents with a budget and then update the budget throughout the survey as they spend it.

I have coded up a toy example to try to get the javascript right here. I am having trouble updating the budget after they spend it in a question.

Here are the questions and the underlying javascript. Can anyone identify where I am going wrong?

Step 0: I set the embedded data field "Budget" to $100 at the beginning of the survey.

Step 1: I display the first page.

*Q1: Your budget is ${e://Field/Budget} This displays correctly.

*Q2: How much to spend? (Open text field, validated as a number.)

Javascript:

{
    
});

Qualtrics.SurveyEngine.addOnReady(function()
{

});

Qualtrics.SurveyEngine.addOnPageSubmit(function(type)
{
    if(type == "next")
    {
            var prevbudget = Qualtrics.SurveyEngine.getEmbeddedData("Budget");
            var prevbudget = parseInt(prevbudget);  
            console.log(prevbudget);
            //var temp = Qualtrics.SurveyEngine.getTextValue("QID2");  //creates an error
            var temp = "${q://QID2/ChoiceTextEntryValue}" 
            console.log(temp) //null
            var temp = parseInt(temp)
            var budget = prevbudget-temp;
            Qualtrics.SurveyEngine.setEmbeddedData('Budget', budget);
    }
});


Qualtrics.SurveyEngine.addOnUnload(function()
{
});

Step 2: I display the next page with updated info.

*Q3: Your budget it ${e://Field/Budget}. not displayed

You previously spent ${q://QID2/ChoiceTextEntryValue}. Displays correctly

*Q4: How much to spend? (Open text field, validated as a number.)

...ideally the process continues with more questions asking for spending and displaying budgets.

It seems to me I am getting something wrong with my understanding of the Qualtrics API or the javascript. Any ideas?


Solution

  • A couple of things:

    1. Pipes are resolved before the page is sent to the browser. So, you can't pipe a value from the current page.
    2. Your budget has to be a number. Adding a '$' in front makes it a string.

    Updated code (assumes budget is a number and the text input is a number):

    Qualtrics.SurveyEngine.addOnPageSubmit(function(type) {
        if(type == "next") {
                var prevbudget = parseInt("${e://Field/Budget}");  
                var temp = parseInt(jQuery("#"+this.questionId+" .InputText").val()); 
                var budget = prevbudget-temp;
                Qualtrics.SurveyEngine.setEmbeddedData('Budget', budget);
        }
    });