Skip to content Skip to sidebar Skip to footer

How To Create A Chained Dropdown And Dynamically Display Results Based On City/state?

I need 2 chained dropdowns, city and state, that would populate a list after choosing the city. So basically a user would be presented with a dropdown to choose a state (US) which

Solution 1:

I think you want something like this:

var citiesByState = {
  USA: ["NY", "NJ"],
  Singapore: ["taas", "naas"]
}

function makeSubmenu(value) {
  if (value.length == 0) document.getElementById("citySelect").innerHTML = "<option></option>";
  else {
    var citiesOptions = "";
    for (cityId in citiesByState[value]) {
      citiesOptions += "<option>" + citiesByState[value][cityId] + "</option>";
    }
    document.getElementById("citySelect").innerHTML = citiesOptions;
  }
}

function resetSelection() {
  document.getElementById("countrySelect").selectedIndex = 0;
  document.getElementById("citySelect").selectedIndex = 0;
}
<body onload="resetSelection()">
  <select id="countrySelect" size="1" onchange="makeSubmenu(this.value)">
    <option></option>
    <option>USA</option>
    <option>Singapore</option>
  </select>
  <select id="citySelect" size="1">
    <option></option>
  </select>
</body>

Note: The options you add in HTML like <option>India</option> must have same name and same cases in JavaScript array like India: ["Gujarat","AP"]

Update :

var citiesByState = {
    USA: ["NY", "NJ"],
    Singapore: ["taas", "naas"]
}

function makeSubmenu(value) {
    if (value.length == 0) document.getElementById("citySelect").innerHTML = "<option></option>";
    else {
        var citiesOptions = "";
        for (cityId in citiesByState[value]) {
            citiesOptions += "<option id=" + citiesByState[value][cityId] + ">" + citiesByState[value][cityId] + "</option>";
        }
        document.getElementById("citySelect").innerHTML = citiesOptions;
    }
}

function makeDisplay(curId)
{
   var curId = curId[curId.selectedIndex].id;
   var elements = document.getElementsByClassName('allbox');
    for (var i = 0; i < elements.length; i++){
        elements[i].style.display = 'none';
    }
   document.getElementById('box'+ curId + '').style.display = 'block';
}
.allbox {
    display:none;
}
<select id="countrySelect" size="1" onchange="makeSubmenu(this.value)">
    <option disabled selected ></option>
    <option>USA</option>
    <option>Singapore</option>
</select>
<select id="citySelect" size="1" onchange="makeDisplay(this)">
    <option></option>
</select>
<div class="allbox" id="boxNY">Some Text... for Ny</div>

<div class="allbox" id="boxNJ">Some Text... for NJ</div>

Post a Comment for "How To Create A Chained Dropdown And Dynamically Display Results Based On City/state?"