Iterate through options of dropdown
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-05-2024 10:17 AM
Hi everyone! I want to iterate through all the options in an existing dropdown/select box. I'm thinking I can do that using
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-06-2024 01:14 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-06-2024 06:39 AM
I can't use getElement because it's apparently deprecated
(g_form) [DEPRECATED] Method getElement is deprecated and unsupported on mobile
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-06-2024 01:15 AM
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);
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-06-2024 06:42 AM
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?