I have seen the clear FAQ on how to dynamically update the options in a dropdown using a call to a standalone page with a PHP action that return the options, but in a CF7 port I wanted to stick with updating the options within javascript code to avoid a major rewrite.
I have found I can do this using Nui.Dropdown.getInstance(field).updateOptions(options) which is working nicely. Here is some dumbed down JS code illustrating this:
myDropdownField = document.getElementById('myDropdownID');
myOptions = new Array();
myOptions[""] = "Select course...";
for (let i = 1 ; i<=3; i++)
{
myOptions["opt-"+i] = "My option text "+i;
}
Nui.Dropdown.getInstance(myDropdownField).updateOptions(myOptions);
I wanted to check if its ok (ie future version proof etc) to use this function from custom JS or if we should stick to the approach demonstrated in the FAQ?
Hi Craig
I think that should be ok, you can also update the select element options and then call this:
Nui.Dropdown.getInstance(select_field).init()
Hi Max, Apologies if I am not implementing this correctly. I have found a couple of problems using NUI Dropown updateOptions() function.
In my test case (uploaded) I build two sets of options with a null key for "no selection" followed by several integer keys for the options. I would expect this is a typical setup where the keys are (say) PKs in a DB table.
I have two problems:
- Problem 1: When the updateOptions() function iterates through current options to grab selected values and then remove the option. It appears that when a selected option is removed the next option automatically set as selected. This is resulting in all options after the first actually selected option become captured as selected. Thus if any of these options are present in the new set of options they are set as selected even though they were not originally.
- Problem 2: The forEach iteration of the options being added are done so in the default Javascript sorted order which puts the null keyed entry at the bottom of the list in the dropdown rather than the top.
I have uploaded a simple form that demonstrates this. A PHP action sets up the two option sets, and the dropdown is initially populated with the first set. There is a radio set to switch between option sets.
For problem 1: I would suggest iterating the current options twice, once to grab options that are actually selected and then again to remove the options.
For problem 2: I have implemented a couple of options I can think of:
- Add an optional sort function that can be passed to updateOptions and then subsequently used in used in Object.keys(options).sort(sortFn)
- Allow passing of an array of option objects so that the order the options are listed in the arrayis preserved.
Simple example switching dropdown sets
