Search code examples
javascripthtmlcombobox

Changing values of a combobox in Javascript


I have a question for Javascipt DOM manipulation. I have written an HTML page that contains two combo boxes. The first combo box contains a list of counties. The second combo box contains a list of cities within the county selected in the first combo box. And I can't figure out how to do the next thing: whenever the value in the fist combo box is changing, the second combo box will be update accordingly. I'd appreciate if somebody can help me, I am a beginner in JS. Thank you!


Solution

  • One of the solutions is as follows but we can show better solutions if you could provide with sample source code.

    var data = [
      { country: 'A',  cities: ['A - 1', 'A - 2', 'A - 3']},
      { country: 'B',  cities: ['B - 1', 'B - 2', 'B - 3']},
      { country: 'C',  cities: ['C - 1', 'C - 2', 'C - 3']}
    ]
    // Need to modify logic based on the data format.
    const getCities = function(selectedCountry) {
      const target = data.find(d => d.country === selectedCountry);
      return target ? target.cities : [];
    }
    
    const changeCities = function (cities) {
      let html = '<option value="-">Cities</option>'
      for (let i in cities) {
        html += '<option value="' + cities[i] + '">' + cities[i] + '</option>'
      }
      document.querySelector('#cities').innerHTML = html;
    }
    
    document.querySelector('#countries').addEventListener('change', (event) => {
      const cities = getCities(event.target.value);
      changeCities(cities);
    });
    <select id="countries">
      <option value="-">Countries</option>
      <option value="A">A</option>
      <option value="B">B</option>
      <option value="C">C</option>
    </select>
    <select id="cities">
      <option value="-">Cities</option>
    </select>