Javascript 用于选择国家和州的下拉菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11483387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:00:32  来源:igfitidea点击:

Drop down menu for selecting country then states

javascripthtmldrop-down-menuhtml-select

提问by Leo

I want a to create a drop down menu which generates another drop down menu on the base of selected value Just for example if select United States from the 1st drop down then 2nd drop down contains the states of United states. I've done much of the job. I am prefering a javascript and using arrays

我想要创建一个下拉菜单,它会根据所选值生成另一个下拉菜单,例如,如果从第一个下拉列表中选择美国,那么第二个下拉列表包含美国的州。我已经完成了大部分工作。我更喜欢 javascript 并使用数组

var country_arr = new Array("USA", "Singapore", "Pakistan")
var s_a = new Array();
s_a[0]="";
s_a[1]="CA|NJ|NY";
s_a[2]="paas|naas|taas";
s_a[3]="Islamabad|karachi|lahore";

But I also want the "name" of the country and state selected, for sending to mysql database. I guess i've to use double dimensional array for this. But unable to code this time and seriously need your help.

但我也想要选择国家和州的“名称”,以发送到 mysql 数据库。我想我必须为此使用二维数组。但是这次无法编码,非常需要您的帮助。

回答by Michael Besteck

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        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 displaySelected() {
            var country = document.getElementById("countrySelect").value;
            var city = document.getElementById("citySelect").value;
            alert(country+"\n"+city);
        }
        function resetSelection() {
            document.getElementById("countrySelect").selectedIndex = 0;
            document.getElementById("citySelect").selectedIndex = 0;
        }
    </script>
</head>
<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>
    <button onclick="displaySelected()">show selected</button>
</body>
</html>