【问题标题】:Populate list of counties drop down after selecting country选择国家后填充县列表
【发布时间】:2012-11-30 14:45:56
【问题描述】:

我有一个旧的 JavaScript 代码,它应该允许用户先选择一个国家,然后再激活该国家选项的县列表。在加载时,国家的选项显示为 ANY,而县标签的选项应显示首先选择选择国家,但事实并非如此。只有当用户先选择一个国家然后返回选择 ANY 时,才会出现先选择一个县的条件。

我一点都不擅长 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> 

【问题讨论】:

  • 我还没有真正彻底检查过这个,但我猜你的counties_dropdown 地图应该有与你的选项具有相同值的键。也就是说,而不是ENGIRL等,它们应该是ENGLANDIRELAND等......而且,您的代码中没有jQuery。
  • 是的,目前还没有 jQuery。我在问我是否可以使用 jQuery 轻松实现这一目标,并且代码少得多。至于键,它似乎在页面上工作正常;例如,当您选择英格兰时,将出现英格兰的县列表。

标签: javascript jquery html-select


【解决方案1】:

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

  var counties = {
    'ENGLAND': {
      'BDF': 'Bedfordshire',
      'BRK': 'Berkshire',
      ...
    },
    'IRELAND': {
      'ANT': 'Antrim',
      'ARM': 'Armagh',
      ...
    },
    'SCOTLAND': {
      'ABD': 'Aberdeenshire',
      'ARL': 'Argyllshire',
      ...
    },
    'WALES': {
      'AGY': 'Anglesey',
      'BRE': 'Brecknockshire',
      ...
    }
  };

您现在可以使用国家/地区选择值中的键来驱动它并填充县下拉列表。观察国家变化,可以使用jQuery的.change()函数。

我建议阅读jQuery API 文档并进行实验。让 SO 用户回答您的问题,您不会进步太多!但是,也就是说,这是我的工作解决方案:http://jsfiddle.net/pfYEb/

【讨论】:

  • 非常感谢您的帮助和示例。如果我在一个页面上有两个使用国家和县域字段的表格,我可以问怎么办?一个基本选项卡和一个高级选项卡。当我在它们之间切换时,似乎有些东西正在影响功能。当我只在页面上使用一次时,请对待您的 jQuery 示例。
  • 我的例子不是复制粘贴工作;它应该指导您如何完成。我不知道您的确切情况,所以我无法调试您的确切问题,但很明显,如果您在同一页面上有两个表单,您将不得不适当地修改我的示例。我能给你的最好建议是下载一些不错的开发工具(Firebug、Chrome DevTools 等),阅读 JS 文档并进行实验。如果您仍然无法使其正常工作,请在 SO 上发布另一个问题,并附上相关详细信息、您尝​​试过的代码以及任何调试器输出,然后有人会引导您朝着正确的方向前进。
  • 我确实发现了这个问题。感谢您的帮助。
【解决方案2】:

有很多不同的方法可以解决这个问题,但一种简单的方法是在 HTML 中硬编码初始状态,然后在需要时用 Javascript 覆盖它。

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

【讨论】:

  • 好吧,我就是这么做的。但仍然显示该县的其他选项。我如何覆盖,什么?抱歉真的不熟悉 JavaScript。
  • 查看 Hakan Hastekin 和 Xophmeister 对 JavaScript 和 jQuery 实现的回答。请注意,Hakan 的解决方案实际上不需要 jQuery。 Xophmeister 推荐阅读 jQuery API。此外,他们documentation 页面中的“入门”部分对初学者很友好。另一个建议是,如果您不熟悉 JavaScript,请先阅读教程或介绍。 jQuery 是用 JavaScript 编写的,所以如果你从对 JavaScript 的基本了解开始,那么 jQuery 会更有意义。
【解决方案3】:

给你,还添加了一些 cmets。测试工作。

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多