4

I am practising programming in JavaScript and I have found a problem that must be answered by some experts regarding drop-down boxes.

The Scenario is:

I have a drop-down box that gives some possible options for provinces and also a second one (town) which depends only on what is selected in the provinces drop-down.

Is there a way in JavaScript that when I chose among provinces, the second drop-down gives the options from the province selected?

robbmj
  • 16,085
  • 8
  • 38
  • 63
arreojn
  • 43
  • 1
  • 1
  • 4

1 Answers1

3

Here is a simple example to get you started.

It works by attaching an event listener for the change event to the province dropdown, then looks up what towns are in that province via the provs object.

See the comments for a detailed explanation of what each line does.

window.onload = function() {
  // provs is an object but you can think of it as a lookup table
  var provs = {
        'British Columbia': ['Victoria', 'Sanitch'],
        'Ontario': ['Bracebridge', 'Waterloo']
      },
      // just grab references to the two drop-downs
      prov_select = document.querySelector('#prov'),
      town_select = document.querySelector('#town');

  // populate the provinces drop-down
  setOptions(prov_select, Object.keys(provs));
  // populate the town drop-down
  setOptions(town_select, provs[prov_select.value]);
  
  // attach a change event listener to the provinces drop-down
  prov_select.addEventListener('change', function() {
    // get the towns in the selected province
    setOptions(town_select, provs[prov_select.value]);
  });
    
  function setOptions(dropDown, options) {
    // clear out any existing values
    dropDown.innerHTML = '';
    // insert the new options into the drop-down
    options.forEach(function(value) {
      dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
    });
  }  
};
<select id="prov"></select>
<select id="town"></select>
robbmj
  • 16,085
  • 8
  • 38
  • 63