Search code examples
javascriptqualtrics

How do you apply the same javascript code to multiple questions in Qualtrics survey?


I have some javascript in one of my survey questions that changes the formatting of a certain field. It works great, but I would like to apply the same code to several other questions. Obviously, I can simply copy and paste onto each question, but is there any way to have the code set in a single location so that it is more maintainable? I've looked on a number of forums but haven't been able to find a solution. Thanks in advance for your help.

EDIT: Here is the JavaScript code that I would like to be repeated for multiple questions:

{
    /*Place your JavaScript here to run when the page is fully displayed*/
    jQuery("#"+this.questionId+" select option:first-child").text("Select one");    

    jQuery("#"+ this.questionId + " option").each(function () {
            if (jQuery(this).text().includes("\"\"")) {
                jQuery(this).hide();    
            }else{
                title = jQuery(this).text()
                title = title.match(/".*"/)
                if(title != null && title[0].length > 30){
                    newTitle = title[0].match(/^.{30}.*?\s/)[0]
                    if(newTitle != title){
                        newTitle = newTitle + "...\""
                    }
                    text = jQuery(this).text()
                    jQuery(this).text(text.replace(title[0],newTitle))
                }   
            }
    });

});

Basically, there is some embedded data preloaded for each contact, and several questions involve a dropdown menu that allows users to select which of their data elements was relevant to a project. This code ensures that blank or missing data does not get included in the dropdown, and also if the option is too many characters long, it gets truncated. Multiple questions include the same dropdown options, but differ in other ways.


Solution

  • Make your code a function and put it in the Qualtrics header. Call the function from each question where it applies.

    In the header:

    <script>
    myFunction(qobj) {
       jQuery("#"+qobj.questionId+" select option:first-child")...etc...
    }
    </script>
    

    Then in your questions:

    Qualtrics.SurveyEngine.addOnload(function() {
      myFunction(this);
    });