Auto-updating dropdown fields in javascript

In this post we’ll explore the use of JavaScript to automatically update dropdown fields based on the input of the previous field. For an example, see the codepen example below:

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”dWqyma” default_tab=”result” user=”benalexkeen”]See the Pen dWqyma by Ben (@benalexkeen) on CodePen.[/codepen_embed]

First we’ll create our form. We have 3 dropdown lists (DDL) fields and each one will update based on the input of the previous fields.


<form>
  <select id="ddl1" onchange="configureDDL2(this, document.getElementById('ddl2'), document.getElementById('ddl3'))">
    <option value="">Pick First Option</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <select id="ddl2" onchange="configureDDL3(document.getElementById('ddl1'), this, document.getElementById('ddl3'))">
  </select>
  <select id="ddl3">
  </select>
</form>

So notice that on changing ddl1, configureDDL2 is called. Similarly when changing ddl2, configureDDL3 is called.

Our options will just be a nested structure of values:


    var myNestedVals = {
        '1': {
            '1.1': ['1.1.1', '1.1.2', '1.1.3'],
            '1.2': ['1.2.1', '1.2.2', '1.2.3'],
            '1.3': ['1.3.1', '1.3.2', '1.3.3']
        },
        '2': {
            '2.1': ['2.1.1', '2.1.2', '2.1.3'],
            '2.2': ['2.2.1', '2.2.2', '2.2.3'],
            '2.3': ['2.3.1', '2.3.2', '2.3.3']
        },
        '3': {
            '3.1': ['3.1.1', '3.1.2', '3.1.3'],
            '3.2': ['3.2.1', '3.2.2', '3.2.3'],
            '3.3': ['3.3.1', '3.3.2', '3.3.3']
        }
    }

Now we can write the rest of our javascript, with our functions to auto-fill the other parts of the form.

We need the values of the previous options chosen for ddl1 and ddl2 when we populate ddl3.

When we call configureDDL2 or configureDDL3, we will want to reset the values of each subsequent dropdown menu and populate the next dropdown menu with the appropriate values.


    function createOption(ddl, text, value) {
        var opt = document.createElement('option');
        opt.value = value;
        opt.text = text;
        ddl.options.add(opt);
    }

    function createOptions(optionsArray, ddl) {
        for (i = 0; i < optionsArray.length; i++) {
            createOption(ddl, optionsArray[i], optionsArray[i]);
        }
    }

    function configureDDL2(ddl1, ddl2, ddl3) {
        ddl2.options.length = 0;
        ddl3.options.length = 0;
        createOption(ddl2, "Pick 2nd Option", "");
        var ddl2keys = Object.keys(myNestedVals[ddl1.value]);
        createOptions(ddl2keys, ddl2)
    }

    function configureDDL3(ddl1, ddl2, ddl3) {
        ddl3.options.length = 0;
        createOption(ddl3, "Pick 3rd Option", "");
        var ddl3keys = myNestedVals[ddl1.value][ddl2.value];
        createOptions(ddl3keys, ddl3);
    }