Javascript Shift Dropdown Options Based on Another Dropdown List

I do JavaScript programming, and I have found a problem that some block experts should answer drop-down.

Scenario:

I have a field drop-downthat gives some possible options for the provinces, as well as a second (city), which depends only on what is selected in the provinces drop-down.

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

+4
source share
1 answer

Here is a simple example to get you started.

, change , , provs.

. , .

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>
Hide result
+2

Source: https://habr.com/ru/post/1584059/


All Articles