forms - Javascript change drop-down box options based on another drop-down box value -


this question has answer here:

i practising programming in javascript , have found problem must answered experts regarding drop-down boxes.

the scenario is:

i have drop-down box gives possible options provinces , second 1 (town) depends on selected in provinces drop-down.

is there way in javascript when chose among provinces, second drop-down gives options province selected?

here simple example started.

it works attaching event listener change event province dropdown, looks towns in province via provs object.

see comments detailed explanation of each line does.

window.onload = function() {    // provs object can think of lookup table    var provs = {          'british columbia': ['victoria', 'sanitch'],          'ontario': ['bracebridge', 'waterloo']        },        // grab references 2 drop-downs        prov_select = document.queryselector('#prov'),        town_select = document.queryselector('#town');      // populate provinces drop-down    setoptions(prov_select, object.keys(provs));    // populate town drop-down    setoptions(town_select, provs[prov_select.value]);        // attach change event listener provinces drop-down    prov_select.addeventlistener('change', function() {      // towns in selected province      setoptions(town_select, provs[prov_select.value]);    });          function setoptions(dropdown, options) {      // clear out existing values      dropdown.innerhtml = '';      // insert new options drop-down      options.foreach(function(value) {        dropdown.innerhtml += '<option name="' + value + '">' + value + '</option>';      });    }    };
<select id="prov"></select>  <select id="town"></select>


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -