简体   繁体   English

根据在另一个下拉列表中所做的选择填充一个下拉列表

[英]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. 在此平台上enter code here是新的(真的是真的),所以请原谅我会犯的任何错误。 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. 我已经为州(我放入了36个州)和另一个州(尽管其中没有选项)创建了下拉列表,但不知道如何编写在一个州创建城市选项的代码。 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: 浏览器说未定义变量oStatename:

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. 这是在javascript和html中添加注释的方法。 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 使用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 : 可以使用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 http://codetomake.com/tools/html/run.php?s=exercise-jquery-select-example-1&f=18

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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