Change one of the form field to dropdown | XM Community
Skip to main content

Hi all

 

I need to convert one of the form field (2nd field) to dropdown. I try to search and did not manage and did not understand why the script does not work.

below is my Javascript. But it still did not change to the dropdown, 

 

Qualtrics.SurveyEngine.addOnload(function() {
    var qid = this.questionId;

    // Define the dropdown element and options
    var dropdown = `
        <select id="QID31-2">
            <option value="">Select an option</option>
            <option value="tech_data">Tech data (affected)</option>
            <option value="non_tech_data">Non-tech data (affected)</option>
            <option value="not_affected">Not affected</option>
        </select>
    `;

    // Insert the dropdown after the second field and hide the original input
    jQuery(dropdown).insertAfter("#" + qid + " .InputText(name='QID31-2']");
    jQuery("#" + qid + " .InputText2name='QID31-2']").hide();

    // Ensure that the dropdown element exists before attaching the onchange event listener
    var dropdownElement = jQuery("#QID31-2");
    if (dropdownElement.length) {  // Ensure the element exists
        dropdownElement.on('change', function() {
            var selectedValue = dropdownElement.val();  // Get the selected value
            jQuery("#" + qid + " .InputTexttname='QID31-2']").val(selectedValue);  // Update the hidden input with the dropdown value
        });
    }

    // Optional: Style the dropdown with Select2 (check if Select2 is loaded)
    if (jQuery().select2) { // Check if Select2 is loaded
        dropdownElement.select2({
            placeholder: 'Select an option',
            width: '200px'
        });
    }
});

Qualtrics.SurveyEngine.addOnReady(function() {
    // Additional JavaScript to run when the page is fully loaded (if needed)
});

Qualtrics.SurveyEngine.addOnUnload(function() {
    // JavaScript to run when the page is unloaded (if needed)
});

 

can advise?

Hi ​@MohamedAli ,

 

The JS code should be  under addOnReady function.

I have tried it in one of my survey and below is the code i used - 

Qualtrics.SurveyEngine.addOnReady(function()
{
    /*Place your JavaScript here to run when the page is fully displayed*/
    var that=this.questionId;
var element="<select id='s1'><option ></option><option value='1'>0<option value='2'>1<option value='3'>2<option value='4'>3+<option value='5'>Unknown</select>";
    jQuery(element).insertAfter("#"+that+" .InputText:eq(2)");
 
    jQuery("#"+that+" .InputText:eq(2)").hide();
    jQuery("#"+that+" .InputText:eq(2)").val(jQuery("#s1 option:selected").text());
 
    jQuery("#s1").on('change',function(){
    jQuery("#"+that+" .InputText:eq(2)").val(jQuery("#s1 option:selected").text());
        
    });
    });

and it worked perfectly.

 

Let me know if you have any queries.


Leave a Reply