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.

<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
      var selCountry = selElem.options[selElem.selectedIndex].value
      var opt
      switch (selCountry) {  // get the correct list
        case "usa":
          opt = opt1
        case "mex":
          opt = opt2
        case "can":
          opt = opt3

      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]
    }  // selElem
  }  // displayElem

  <select id="country" onchange="displayCity('country','city')">
  <option value="usa">USA</option>
  <option value="mex">Mexico</option>
  <option value="can">Canada</option>
  <select id="city">

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

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.