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"]
}
functionmakeSubmenu(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;
}
}
functionresetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").selectedIndex = 0;
}
<bodyonload="resetSelection()"><selectid="countrySelect"size="1"onchange="makeSubmenu(this.value)"><option></option><option>USA</option><option>Singapore</option></select><selectid="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 JavaScriptarray
likeIndia: ["Gujarat","AP"]
Update :
var citiesByState = {
USA: ["NY", "NJ"],
Singapore: ["taas", "naas"]
}
functionmakeSubmenu(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;
}
}
functionmakeDisplay(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;
}
<selectid="countrySelect"size="1"onchange="makeSubmenu(this.value)"><optiondisabledselected ></option><option>USA</option><option>Singapore</option></select><selectid="citySelect"size="1"onchange="makeDisplay(this)"><option></option></select><divclass="allbox"id="boxNY">Some Text... for Ny</div><divclass="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?"