Javascript 选择国家/地区后,填充县列表下拉列表

Javascript 选择国家/地区后,填充县列表下拉列表,javascript,jquery,html-select,Javascript,Jquery,Html Select,我有一个旧的JavaScript代码,它应该允许用户首先选择一个国家,然后激活该国家的县列表选项。加载时,国家的选项表示“任何”,县标签的选项应表示“先选择一个国家”,但不表示“选择一个国家”。仅当用户先选择一个国家,然后再返回选择任何国家时,才会出现先选择一个县的条件 我对JavaScript一窍不通,更不用说jQuery了。如何纠正现有的js,甚至用更好的精益代码实现我想要的 提前谢谢你的帮助 <div> <label id="country">Country o

我有一个旧的JavaScript代码,它应该允许用户首先选择一个国家,然后激活该国家的县列表选项。加载时,国家的选项表示“任何”,县标签的选项应表示“先选择一个国家”,但不表示“选择一个国家”。仅当用户先选择一个国家,然后再返回选择任何国家时,才会出现先选择一个县的条件

我对JavaScript一窍不通,更不用说jQuery了。如何纠正现有的js,甚至用更好的精益代码实现我想要的

提前谢谢你的帮助

<div>
  <label id="country">Country of birth:</label>
  <select name="country"  tabindex="7" onchange="populateCountiesDropdown(this[this.selectedIndex].value);">
    <option value="">Any</option>
    <option value="ENGLAND">England</option>
    <option value="IRELAND">Ireland</option>
    <option value="SCOTLAND">Scotland</option>
    <option value="WALES">Wales</option>
  </select>
  <script type="text/javascript">
        setSelect(document.main.country, '');
</script> 
</div>
<div>
  <label id="county">County of birth:</label>
  <select name="county"  tabindex="8">
  </select>
  <script type="text/javascript">
    populateCountiesDropdown(document.main.country.value);
    setSelect(document.main.county, "");
</script> 
</div>
<script type="text/javascript">
    var counties_dropdown = new Array(); 

        counties_dropdown["ENG"] = new Array("   |All counties in country" ,"BDF|Bedfordshire","BRK|Berkshire","BKM|Buckinghamshire","CAM|Cambridgeshire","CHI|Channel Islands","CHS|Cheshire","CON|Cornwall","CUL|Cumberland","DBY|Derbyshire","DEV|Devon","DOR|Dorset","DUR|Durham","ESS|Essex","GLS|Gloucestershire","HAM|Hampshire","HEF|Herefordshire","HRT|Hertfordshire","HUN|Huntingdonshire","IOM|Isle of Man","KEN|Kent","LAN|Lancashire","LEI|Leicestershire","LIN|Lincolnshire","LND|London","MDX|Middlesex","NFK|Norfolk","NTH|Northamptonshire","NBL|Northumberland","NTT|Nottinghamshire","OXF|Oxfordshire","RUT|Rutlandshire","SAL|Shropshire","SOM|Somerset","STS|Staffordshire","SFK|Suffolk","SRY|Surrey","SSX|Sussex","WAR|Warwickshire","WES|Westmorland","WIL|Wiltshire","WOR|Worcestershire","YKS|Yorkshire" );

        counties_dropdown["IRL"] = new Array("   |All counties in country" ,"ANT|Antrim","ARM|Armagh","CAR|Carlow","CAV|Cavan","CLA|Clare","COR|Cork","LDY|Derry (Londonderry)","DON|Donegal","DOW|Down","DUB|Dublin","FER|Fermanagh","GAL|Galway","KER|Kerry","KID|Kildare","KIK|Kilkenny","OFF|Kings (Offaly)","LET|Leitrim","LIM|Limerick","LOG|Longford","LOU|Louth","MAY|Mayo","MEA|Meath","MOG|Monaghan","NAI|Nairnshire","LEX|Queens (Laois)","ROS|Roscommon","SLI|Sligo","TIP|Tipperary","TYR|Tyrone","WAT|Waterford","WEM|Westmeath","WEX|Wexford","WIC|Wicklow" );

        counties_dropdown["SCT"] = new Array("   |All counties in country" ,"ABD|Aberdeenshire","ARL|Argyllshire","AYR|Ayrshire","BAN|Banffshire","BEW|Berwickshire","BUT|Buteshire","CAI|Caithness","CLK|Clackmannanshire","DFS|Dumfriesshire","DNB|Dunbartonshire","FIF|Fife","ANS|Forfarshire (Angus)","ELN|Haddingtonshire (East Lothian)","INV|Invernessshire","KCD|Kincardineshire","KRS|Kinrossshire","KKD|Kirkcudbrightshire","LKS|Lanarkshire","WLN|Linlithgowshire (West Lothian)","MLN|Midlothian","MOR|Morayshire","PEE|Peeblesshire","PER|Perthshire","RFW|Renfrewshire","ROC|Ross and Cromarty","ROX|Roxburghshire","SEL|Selkirkshire","SHI|Shetland Islands","STI|Stirlingshire","SUT|Sutherland","WIG|Wigtownshire" );

        counties_dropdown["WLS"] = new Array("   |All counties in country" ,"AGY|Anglesey","BRE|Brecknockshire","CAE|Caernarvonshire","CGN|Cardiganshire","CMN|Carmarthenshire","DEN|Denbighshire","FLN|Flintshire","GLA|Glamorganshire","MER|Merionethshire","MON|Monmouthshire","MGY|Montgomeryshire","PEM|Pembrokeshire","RAD|Radnorshire" );

    function populateCountiesDropdown(formObj, country) {
        formObj.county.options.length = 0;
        if(country == "") {
            formObj.county.options[0] = new Option('Choose a country first', '');
            return;
        }
        for(i = 0; i < counties_dropdown[country].length; i++) {
            var option = new Option(counties_dropdown[country][i].substr(counties_dropdown[country][i].indexOf('|')+1), 
                                    counties_dropdown[country][i].substr(0,counties_dropdown[country][i].indexOf('|')));
            formObj.county.options[i] = option;
        }
        formObj.county.options[0].value = '';
    }
</script> 

出生国:
任何
英格兰
爱尔兰
苏格兰
威尔士
setSelect(document.main.country“”);
出生地:
PopulateCountries下拉列表(document.main.country.value);
setSelect(document.main.county,“”);
var\u下拉列表=新数组();
县下拉列表[“ENG”]=新数组(“全国所有县”、“贝德福德郡”、“伯克希尔郡”、“白金汉郡”、“坎布里奇郡”、“奇奇海峡群岛”、“柴郡”、“康沃尔郡”、“坎伯兰郡”、“德比郡”、“德文郡”、“多塞特郡”、“杜尔达勒姆郡”、“埃塞克斯郡”、“格洛斯特郡”、“汉普郡”,“赫特福德郡、亨廷顿郡、马恩岛、肯特郡、兰开夏郡、莱斯特郡、林克郡、伦敦、米德尔塞克斯郡、诺福克郡、北安普敦郡、诺森伯兰郡、诺丁汉郡、诺丁汉郡、牛津郡、拉特兰郡、萨尔斯多夫郡、萨福克郡、萨福克郡、萨福克郡、萨福克郡、诺丁汉郡、诺丁汉郡、牛津郡、牛津郡、罗特、拉特兰郡、萨福克郡”萨里郡、苏塞克斯郡、沃里克郡、韦斯特摩兰郡、威尔特郡、伍斯特郡、约克郡);
“IRL”的下降下降(IRL)的下降下降(IRL)的下降下降(IRL)的下降(IRL)的下降(IRL)的下降(IRL)的下降(IRL)的下降(IRL)的下降(IRL)的新阵列(新阵列)的新阵列(新阵列)的新阵列(新阵列)新阵列(新阵列)新阵列(新阵列)新阵列(新阵列)新阵列(包括:所有国家中的所有县)的国家,包括:国家,所有国家,所有县,国家,国家,国家,国家,国家,国家,国家,国家,国家,蚂蚁,蚂蚁,蚂蚁,ANT,安提姆,安提姆,安提姆,安提姆,安提姆,安提姆,军队,手臂,手臂,手臂,手臂,手臂,手臂,手臂,阿马,手臂,手臂,手臂,手臂,手臂,阿马,汽车,汽车,汽车,汽车,汽车,卡尔,汽车,卡诺,汽车,卡诺,汽车,汽车,卡诺,汽车,卡诺,|朗福德“卢|卢斯、梅|梅奥、米埃、莫纳汉、奈恩郡、莱克斯皇后区、罗斯康姆、斯莱戈、蒂佩拉里、提尔·蒂龙、沃特福德、韦姆·韦斯特米斯、韦克斯福德、威克洛);
县下拉列表[“SCT”]=新数组(“全国所有县”、“阿布德阿伯丁郡”、“阿尔金郡”、“艾尔艾尔郡”、“班夫郡”、“贝威克郡”、“布特希尔郡”、“蔡斯凯尼斯郡”、“克拉克曼南希尔郡”、“杜姆弗里斯郡”、“丹巴顿郡”、“国际足联法夫郡”、“法兰斯郡”、“福法尔郡(安格斯)”、“东哈得兰郡”、“因弗森郡”KCD金卡丁郡、KRS金罗斯郡、KKD基尔库布利特郡、LKS拉纳克郡、WLN林利特戈斯郡(西洛锡安)、MLN米德洛锡安郡、莫尔马里郡、皮尔斯郡、佩尔珀斯郡、RFW伦弗鲁斯郡、罗克罗斯和克罗马蒂郡、罗克斯堡郡、塞尔基尔克郡、锡兰群岛、萨特兰、萨特兰郡、斯特维希郡" );
县下拉列表[“WLS”]=新阵列(“全国所有县”、“阿吉·安格西”、“布雷·布雷克什尔”、“卡埃纳尔文郡”、“CGN开襟羊毛衫郡”、“CMN卡马森郡”、“登比格郡”、“弗林茨郡”、“格拉·格拉摩根郡”、“梅里奥尼特郡”、“蒙茅斯郡”、“蒙哥马利郡”、“彭布罗克郡”、“诺拉郡”);
函数PopulateCountries下拉列表(formObj,国家){
formObj.country.options.length=0;
如果(国家==“”){
formObj.country.options[0]=新选项('Choose a country first','');
返回;
}
对于(i=0;i
有许多不同的方法可以实现这一点,但一种简单的方法是用HTML硬编码初始状态,然后在需要时用Javascript覆盖它

<select name="county"  tabindex="8">
  <option>Choose a country first</option>
</select>

先选择一个国家

正如您在评论中所建议的那样,使用jQuery肯定会使代码更易于阅读。但是,在我看来,您可以进行的最佳优化是在县数据结构中:将其作为一个地图,而不是一个项目由管道字符分隔的数组,然后必须拆分。即:

  var counties = {
    'ENGLAND': {
      'BDF': 'Bedfordshire',
      'BRK': 'Berkshire',
      ...
    },
    'IRELAND': {
      'ANT': 'Antrim',
      'ARM': 'Armagh',
      ...
    },
    'SCOTLAND': {
      'ABD': 'Aberdeenshire',
      'ARL': 'Argyllshire',
      ...
    },
    'WALES': {
      'AGY': 'Anglesey',
      'BRE': 'Brecknockshire',
      ...
    }
  };
现在,您可以使用country select的值中的键来驱动此操作并填充county下拉列表。要查看国家/地区的变化,可以使用jQuery的
.change()
函数


我建议阅读文档并进行实验。让如此多的用户回答你的问题,你不会进步很多!不过,也就是说,这是我的工作解决方案:

给你,也添加了一些评论。测试工作

<script type="text/javascript">
    var counties_dropdown = new Array();
    counties_dropdown["ENG"] = new Array("   |All counties in country", "BDF|Bedfordshire", "BRK|Berkshire", "BKM|Buckinghamshire", "CAM|Cambridgeshire", "CHI|Channel Islands", "CHS|Cheshire", "CON|Cornwall", "CUL|Cumberland", "DBY|Derbyshire", "DEV|Devon", "DOR|Dorset", "DUR|Durham", "ESS|Essex", "GLS|Gloucestershire", "HAM|Hampshire", "HEF|Herefordshire", "HRT|Hertfordshire", "HUN|Huntingdonshire", "IOM|Isle of Man", "KEN|Kent", "LAN|Lancashire", "LEI|Leicestershire", "LIN|Lincolnshire", "LND|London", "MDX|Middlesex", "NFK|Norfolk", "NTH|Northamptonshire", "NBL|Northumberland", "NTT|Nottinghamshire", "OXF|Oxfordshire", "RUT|Rutlandshire", "SAL|Shropshire", "SOM|Somerset", "STS|Staffordshire", "SFK|Suffolk", "SRY|Surrey", "SSX|Sussex", "WAR|Warwickshire", "WES|Westmorland", "WIL|Wiltshire", "WOR|Worcestershire", "YKS|Yorkshire");
    counties_dropdown["IRL"] = new Array("   |All counties in country", "ANT|Antrim", "ARM|Armagh", "CAR|Carlow", "CAV|Cavan", "CLA|Clare", "COR|Cork", "LDY|Derry (Londonderry)", "DON|Donegal", "DOW|Down", "DUB|Dublin", "FER|Fermanagh", "GAL|Galway", "KER|Kerry", "KID|Kildare", "KIK|Kilkenny", "OFF|Kings (Offaly)", "LET|Leitrim", "LIM|Limerick", "LOG|Longford", "LOU|Louth", "MAY|Mayo", "MEA|Meath", "MOG|Monaghan", "NAI|Nairnshire", "LEX|Queens (Laois)", "ROS|Roscommon", "SLI|Sligo", "TIP|Tipperary", "TYR|Tyrone", "WAT|Waterford", "WEM|Westmeath", "WEX|Wexford", "WIC|Wicklow");
    counties_dropdown["SCT"] = new Array("   |All counties in country", "ABD|Aberdeenshire", "ARL|Argyllshire", "AYR|Ayrshire", "BAN|Banffshire", "BEW|Berwickshire", "BUT|Buteshire", "CAI|Caithness", "CLK|Clackmannanshire", "DFS|Dumfriesshire", "DNB|Dunbartonshire", "FIF|Fife", "ANS|Forfarshire (Angus)", "ELN|Haddingtonshire (East Lothian)", "INV|Invernessshire", "KCD|Kincardineshire", "KRS|Kinrossshire", "KKD|Kirkcudbrightshire", "LKS|Lanarkshire", "WLN|Linlithgowshire (West Lothian)", "MLN|Midlothian", "MOR|Morayshire", "PEE|Peeblesshire", "PER|Perthshire", "RFW|Renfrewshire", "ROC|Ross and Cromarty", "ROX|Roxburghshire", "SEL|Selkirkshire", "SHI|Shetland Islands", "STI|Stirlingshire", "SUT|Sutherland", "WIG|Wigtownshire");
    counties_dropdown["WLS"] = new Array("   |All counties in country", "AGY|Anglesey", "BRE|Brecknockshire", "CAE|Caernarvonshire", "CGN|Cardiganshire", "CMN|Carmarthenshire", "DEN|Denbighshire", "FLN|Flintshire", "GLA|Glamorganshire", "MER|Merionethshire", "MON|Monmouthshire", "MGY|Montgomeryshire", "PEM|Pembrokeshire", "RAD|Radnorshire");

    function populateCountiesDropdown(country) {
        // get the html element
        var select = document.getElementById("county");

        // remove all options from select
        select.options.length = 0;

        if (country == "") {
            select.options[0] = new Option('Choose a country first', '');
            return;
        }
        for (i = 0; i < counties_dropdown[country].length; i++) {

            // split the element of county array
            // for example after split county array will contain
            // county[0] = 'BDF',
            // county[1] = 'Bedfordshire',
            var county = counties_dropdown[country][i].split('|');

            // add a new option to the select by inserting it to the index of length
            // note that length is zero based, so current length would be the index that you need to
            // add the new option.
            select.options[select.options.length] = new Option(county[1], county[0]);
        }
    }
</script>
<div>
    <label for="country">Country of birth:</label>
    <select id="country" name="country" tabindex="7" onchange="populateCountiesDropdown(this[this.selectedIndex].value);">
        <option value="" selected="selected">Any</option>
        <option value="ENG">England</option>
        <option value="IRL">Ireland</option>
        <option value="SCT">Scotland</option>
        <option value="WLS">Wales</option>
    </select>
</div>
<div>
    <label for="county">County of birth:</label>
    <select id="county">
        <option value=""> Choose a country first</option>
    </select>
</div>

var\u下拉列表=新数组();
县下拉列表[“ENG”]=新数组(“全国所有县”、“贝德福德郡”、“伯克希尔郡”、“白金汉郡”、“坎布里奇郡”、“奇海峡群岛”、“柴郡”、“康沃尔郡”、“康沃尔郡”、“坎伯兰郡”、“德比郡”、“德文郡”、“多塞特郡”、“杜尔达勒姆郡”、“埃塞克斯郡”、“格洛斯特郡”、“汉普郡”,“赫里福德郡”、“赫里福德郡”、“亨廷顿郡”、“曼恩岛”、“肯特郡”、“兰开夏郡”、“莱斯特郡”、“林克伦郡”、“伦敦”、“米德尔塞克斯郡”、“米德尔塞克斯郡”、“诺福克郡”、“北安普敦郡”、“北安普敦郡”、“诺森伯兰郡”、“诺丁汉郡”、“牛津郡”、“拉特郡”、“索姆郡”、“萨默斯郡”圣斯塔福德郡、萨福克郡、萨里郡、萨塞克斯郡、沃里克郡、威斯特摩兰郡、威尔特郡、伍斯特郡、约克郡);
Countries|u下拉菜单[“IRL”]=新数组(“|全国所有县”,“ANT | A