The CreatorCon Call for Content is officially open! Get started here.

Iterate through options of dropdown

snexplorer
Tera Contributor

Hi everyone! I want to iterate through all the options in an existing dropdown/select box. I'm thinking I can do that using 

g_form.getControl() but the output of that looks like this:snexplorer_1-1725556295038.png

 

The options array is empty even though the select box variable has multiple question choices tied to it that I'm able to view and select on the form UI. In addition, calling g_form.getElement('request_type') returns undefined.

I'm not sure if I'm calling these methods wrong. Later in my code, I do set the value of the same dropdown element using g_form.setValue('request_type', value) and it does successfully update the dropdown with what I want so I am using the right field name. Does anyone know what I'm doing wrong here? Is my expectation for the output of getControl incorrect?

7 REPLIES 7

debendudas
Mega Sage
Mega Sage

Hi @snexplorer ,

You can use the below client script code:

    var field = g_form.getElement("<field_name>");
    var choices = [];
    for (var i = 0, n = field.options.length; i < n; i++) {
        if (field.options[i].value)
            choices.push(field.options[i].value);
    }

// Now you can use the choices array which contains all the choice values

I can't use getElement because it's apparently deprecated

 (g_form) [DEPRECATED] Method getElement is deprecated and unsupported on mobile

Anurag Tripathi
Mega Patron
Mega Patron

HI,

Something like this should work

var options = g_form.getControl('field_name').options;
for (i=0; i<options.length; i++) {
alert(options<i>.value);
}
-Anurag

Hi Anurag, I'm not able to use use getControl() because, for some reason, the options array is empty, as shown in the screenshot in my original image. I know I'm using the correct field name when calling getControl() because later in my script, I am able to set the dropdown value using g_form.setValue(). The dropdown is filled with 7 question choices. As an experiment, I tried using g_formaddOption() to add options to the dropdown but even after doing this, the options array in from getControll() is empty.

Do you know why options would appear as an empty array?