Hi, I'm fairly new to javascript and am trying to figure a relatively simple thing out. I have two drop-down selectors I want to display, one that lists countries and one that lists cities in the selected country. I want it to be the case that on changing the country selector to, e.g., Mexico, the city selector automatically updates to only display Mexican cities in the database without reloading the page. What would be the best way to go about doing this?

A sample code is below.

<html>
<head>
<script type="text/javascript">
var opt1 = ["usCity1","usCity2","usCity3"]
var opt2 = ["mxCity1","mxCity2","mxCity3","mxCity4"]
var opt3 = ["cnCity1","cnCity2","cnCity3","cnCity4","cnCity5"]

function displayCity(selID, subSelID) {
  var dispElem = document.getElementById(subSelID)
  if (dispElem) {  // ensure that display element exists
    var selElem = document.getElementById(selID)
    if (selElem) {  // ensure that source selection element exists
      for (var i=dispElem.options.length-1; i>=0; i--) {  // remove previous children
        dispElem.options[i].parentNode.removeChild(dispElem.options[i])
      }
      var selCountry = selElem.options[selElem.selectedIndex].value
      var opt
      switch (selCountry) {  // get the correct list
        case "usa":
          opt = opt1
        break
        case "mex":
          opt = opt2
        break
        case "can":
          opt = opt3
        break
      }

      for (var i=0; i<opt.length; i++) {  // add to selected elements
        var newElem = document.createElement("option")
        newElem.value = opt[i]
        newElem.innerHTML = opt[i]
        dispElem.appendChild(newElem)
      }
    }  // selElem
  }  // displayElem
}
</script>
</head>

<body>
  Country:&nbsp;
  <select id="country" onchange="displayCity('country','city')">
  <option value="usa">USA</option>
  <option value="mex">Mexico</option>
  <option value="can">Canada</option>
  </select>
  &nbsp;&nbsp;&nbsp;&nbsp;
  City:
  <select id="city">
  </select>

  <script type="text/javascript">
  displayCity("country", "city")
  </script>
</body>
</html>

I use remove & add DOM elements because it tends to be faster than rewriting innerHTML for most browsers. Also, the list (array) is predefined. If you need to obtain the list from the server each time a user selects, you may need to use Ajax.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.