Javascript Executed Twice when NOT in Preview Mode | XM Community
Skip to main content

I've set up a custom drilldown question in my survey that lets people choose their location step by step. They can pick from four dropdown menus, which are filled out by a piece of code that looks like this:

jQuery(document).off('change', '#QID1_dropdown').on('change', '#QID1_dropdown', function () {
    var provinceId = jQuery(this).val();
    Qualtrics.SurveyEngine.setEmbeddedData('provinceId', provinceId);
    if (provinceId) {
        jQuery('#QID2_dropdown').empty().show().append('<option value="">Select City/Regency</option>');
        console.log("Fetching cities/regencies...");

        jQuery.get('https://mybackendwebsite.com/cities_regencies/' + provinceId, function (data) {
            var cityRegencyDropdown = jQuery('#QID2_dropdown');
            console.log("Appending cities/regencies...");
            jQuery.each(data, function (_, item) {
                cityRegencyDropdown.append(new Option(item.city_regency_name, item.city_regency_id));
            });
            console.log("Cities/regencies appended.");
        });
    } else {
        resetAndHideDropdowns(1);
    }
});

(writing the code in paragraph style because code style is ruining the indentation)

However, I'm running into a problem. Even though it seems to work, my computer's console logs show that the code for this question is running twice. This causes each location to show up twice in the dropdown menus, which I don't want.

Here's what I've noticed:

  • Testing: When I check my backend directly by calling my API, everything works fine. So, the issue isn't with my backend.
  • Solution Tried: I've already tried adding a switch in my jQuery code to stop the list from being added twice.
  • When It Happens: This problem shows up after I've published the survey. This is not a preview problem.

Even though this bug doesn't stop the survey from working (people can still pick their locations and the survey records it correctly), it doesn't look good. It can make the survey harder to take because there's too much information, which could tire people out faster. I'd really like to fix this.

Also, I need to ask for very specific location info, which means I have to list more places than the usual 500-limit in a Qualtrics dropdown question. By using my own backend system, I can show these details in four steps instead of just three that Qualtrics usually allows.

Does anyone know if it's a common problem for the JavaScript code to run twice like this, even when not in preview mode? What can I do to fix this?

I think the issue is this line:

cityRegencyDropdown.append(new Option(item.city_regency_name, item.city_regency_id));

You can’t use ‘new Option’ directly with append. You could do this:

cityRegencyDropdown.get(0).add(new Option(item.city_regency_name, item.city_regency_id));

 


Leave a Reply