Dynamic Choices: Nintex Forms

While at work today, I got this great question about how to build dynamic option values in a drop down control based on the output of other drop down controls.

For example,  I have Drop down A, that has two values (X, Y) and I have Drop down  B, that has two values (Green, Red). The third drop down, Drop down C, will have the selected values of both Drop down A and Drop down B as the available options to select. So how do you do this in Nintex Forms? Find out below:

The Build

Open the Nintex Forms Designer and then add three Choice Controls. 

In each drop down, you will then need to give them Client ID JavaScript variable names and for the first two drop downs, add some values. In the first drop down, I'll add  the choice options of my two fellow Americas Technical Evangelist buds, Vadim and Brad. Next, I'll change the Display format to 'Drop down list' and then give it the Client ID JavaScript variable name of 'dd1'.

Now let's take a look at how the second Drop down is configured:

Notice the Client ID JavaScript variable name is 'dd2'. That will be important for our code later on.

Finally, let's take a look at look at how the third Drop down control, with the Client ID variable 'dd3', is configured:

Easy enough, right? Now let's get to the code!

The Code

What we need to do is to change the option values of the 'dd3' drop down control to be whatever the selected values are of 'dd1' and 'dd2'. So we will need to:

  • Latch onto the change event of both of those controls.
  • Store the selected values of both controls.
  • Create and Object to store those values.
  • Remove any values that existed before the change event.
  • Append the new options as the available values for 'dd3'.

So what does that translate to in JavaScript? I'm glad you asked:

NWF$(document).ready(function(){
    var changeMe = NWF$('#' + dd1);
    var changeMe2 = NWF$('#' + dd2);
    NWF$(changeMe).add(changeMe2).click(function(){
        var x = NWF$('#' + dd1 + ' option:selected').val();
        var y = NWF$('#' + dd2 + ' option:selected').val();
        console.log(x + ' ' + y);

        var newChoices = {
            val1 : x,
            val2 : y
        };
        var lastDD = NWF$('#' + dd3);
        lastDD.empty();
        NWF$.each(newChoices, function(val, text){
            lastDD.append(
                NWF$('<option></option>').val(val).html(text)
                );
        });
    });
});

So copy/pasta that bad boy into the Custom JavaScript section of the Form Settings and let's see what happens. 

The Result

I'll go ahead and choose a value for the first two drop downs. The selected values will be the only options available in my third drop down.

I've always fancied a BMW, so let's give only those options.

Give it a try in your Nintex Forms environment! Like always, I'd love to hear your thoughts and questions in the comments section. Thanks for reading!