Javascript DOM Form Select populate

Description

Javascript DOM Form Select populate

View in separate window


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Populating Selection Lists</title>
<script>
  let citystore = new Array();/*from   ww w.  j  a v  a2s  . com*/
  citystore[0] = [ 'CA', 'San Francisco' ];
  citystore[1] = [ 'CA', 'Los Angeles' ];
  citystore[2] = [ 'CA', 'San Diego' ];
  citystore[3] = [ 'MO', 'St. Louis' ];
  citystore[4] = [ 'MO', 'Kansas City' ];
  citystore[5] = [ 'WA', 'Seattle' ];
  citystore[6] = [ 'WA', 'Spokane' ];
  citystore[7] = [ 'WA', 'Redmond' ];

  window.onload = function() {
    document.getElementById("state").onchange = filterCities;
  }

  function filterCities() {
    let state = this.value;
    let city = document.getElementById('cities');
    city.options.length = 0;

    for (let i = 0; i < citystore.length; i++) {
      let st = citystore[i][0];
      if (st == state) {
        let opt = new Option(citystore[i][1]);
        try {
          city.add(opt, null);
        } catch (e) {
          city.add(opt);
        }
      }
    }
  }
</script>
</head>
<body>
  <form id="picker" method="post" action="">
    <select id="state">
      <option value="">--</option>
      <option value="MO">Missouri</option>
      <option value="WA">Washington</option>
      <option value="CA">California</option>
    </select> <select id="cities">
    </select>
  </form>
</body>
</html>



PreviousNext

Related