简体   繁体   中英

Populating a drop-down list according to the selection made in another drop-down list

enter code here am new(really really new) on this platform so forgive me for any errors I will make. I'm trying to make a membership form as practice and I am stuck on how to populate a menu of cities within a state. I have made the drop-down list for the states(i put in 36 states)and another(although there are no options in it) but don't know how to go about writing the code that creates the options of cities in a state. I have many theories in my head but I know that they are all going to be slow and inefficient. An example specific to my situation would do the trick. Thanks in advance!

Here's the last code I wrote. The browser said the variable oStatename wasn't defined:

window.onload=initialize;

function initialize(){
var lgafield=document.getElementById("LGA");
var oStatename=[
{"state":"Abia",
  "lga":["Aba North","Aba South","Arochukwu","Bende","Ikwuano","Isiala-Ngwa 
North",
"Isiala-Ngwa South","Isiukwato","Obi 
Ngwa","Ohafia","Osisioma","Ugwunagbo","Ukwa East","Ukwa West",
"Umuahia North","Umuahia South","Umu-Neochi"]},
//there are more
{"state":"Adamawa",
"lga":
["Demsa","Fufore","Ganaye","Gireri","Gombi","Guyuk","Hong","Jada","Lamurde",
"Madagali","Maiha","Mayo-Belwa","Michika","Mubi North","Mubi 
South","Numan","Shelleng","Song",
"Toungo","Yola North","Yola South"]}
]
var sorfield=document.getElementById("SOR");
sorfield.onchange=getLGA;
}

function getLGA(){
var index=document.getElementById("SOR").selectedIndex;
var selectLGAs=oStatename[index].lga;

for(i in oStatename[index].lga){
    lgafield.options= new Option(oStatename[index].lga[i]);
}
}

Here is how to do it in javascript and html with comments. This solution works with your structure, but there are other ways to organize the States and Cities that could work better (in my opinion).

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script type="text/javascript">

//The dictionary array containing the states and cities
var oStatename=[
{"state":"Abia",
  "lga":["Aba North","Aba South","Arochukwu","Bende","Ikwuano","Isiala-Ngwa North",
"Isiala-Ngwa South","Isiukwato","Obi Ngwa","Ohafia","Osisioma","Ugwunagbo","Ukwa East","Ukwa West",
"Umuahia North","Umuahia South","Umu-Neochi"]},
{"state":"Adamawa",
"lga":
["Demsa","Fufore","Ganaye","Gireri","Gombi","Guyuk","Hong","Jada","Lamurde",
"Madagali","Maiha","Mayo-Belwa","Michika","Mubi North","Mubi South","Numan","Shelleng","Song",
"Toungo","Yola North","Yola South"]}
];

//Function to initialize the options (Populate States and Cities with the cities from 1st state)
window.onload = function(){

    var selState = document.getElementById('selState');//Select State Drop Down List

    //Create all States options
    for(var i = 0; i < oStatename.length; i++)
    {
        createOption(selState, oStatename[i]["state"],oStatename[i]["state"]);//Create State DropDown option
    }

    //Itinialize the 2nd dropdown with cities from 1st state (selected by default)
    configureDropDownLists();

}

//This function populates the city drop down according to the selected state
function configureDropDownLists() {

     var selState = document.getElementById('selState');//Select State Drop Down List
     var selCity = document.getElementById('selCity');// Select City Drop Down List

     selCity.options.length = 0;// reset City Drop Down Options
     for (i = 0; i < oStatename[selState.selectedIndex]["lga"].length; i++) //Create options based on selected state
     {
                createOption(selCity, oStatename[selState.selectedIndex]["lga"][i], oStatename[selState.selectedIndex]["lga"][i]);
     }

}
//Create an option and add it to the drop down list "ddl" with text and value
function createOption(ddl, text, value) {
    var opt = document.createElement('option');
    opt.value = value;
    opt.text = text;
    ddl.options.add(opt);
}
</script>
<body>

<!--link onchange to configureDropDownLists() function-->
<select id="selState" onchange="configureDropDownLists()">
</select>

<select id="selCity">
</select>
</body>
</html>

---Old Answer---

Use http://geodata.solutions

I have generated this code for USA states and cities in less than a minute.

<input type="hidden" name="country" id="countryId" value="US"/>
<select name="state" class="states order-alpha" id="stateId">
    <option value="">Select State</option>
</select>
<select name="city" class="cities order-alpha" id="cityId">
    <option value="">Select City</option>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="//geodata.solutions/includes/statecity.js"></script>

Hope this will help you. It can be done using jQuery :

 $(function(){ $('#states').change(function(){ var Alabama = ["Abbeville", "Adamsville", "Addison", "Akron", "Alabaster"]; var Alaska = ["Anchorage", "Fairbanks", "Juneau", "Sitka", "Ketchikan"]; var Arizona = ["Apache Junction", "Avondale", "Benson", "Buckeye", "Bullhead City"]; var Arkansas = ["Little Rock", "Fort Smith", "Fayetteville", "Springdale", "Jonesboro"]; var option = ''; var str = "var SelectedState = " + this.value; eval(str); for (var i=0;i<SelectedState.length;i++){ option += '<option value="'+ SelectedState[i] + '">' + SelectedState[i] + '</option>'; } var Cities = "<select>" + option + "</select>"; $('#citiesDiv').html(''); $('#citiesDiv').append(Cities); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="states"> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> </select> <div id="citiesDiv"></div> 

http://codetomake.com/tools/html/run.php?s=exercise-jquery-select-example-1&f=18

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM