2012-11-30 138 views
1

我有一箇舊的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> 
+1

我還沒有真正檢查過這個徹底,但我想你的'counties_dropdown'地圖應該有與您的選項相同的值的鍵。也就是說,不是'ENG','IRL'等等,它們應該是'ENGLAND','IRELAND'等等。而且,你的代碼中沒有jQuery。 – Xophmeister

+0

是的,目前沒有jQuery。我問是否可以用jQuery來輕鬆實現,代碼少得多。至於鍵,它似乎在網頁上正常工作;例如,當你選擇英格蘭時,英格蘭的縣名單出現。 – user1400854

回答

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/

+0

非常感謝您的幫助和示例。我可以問,如果我在使用國家和縣字段的頁面上有兩種表單,該怎麼辦?基本選項卡和高級選項卡。當我在它們之間切換時,某些東西似乎正在影響該功能。當我只在頁面上使用它時,請處理您的jQuery示例。 – user1400854

+0

我的例子不是複製和粘貼作業;它應該指導你如何完成它。我不知道你的具體情況,所以我不能調試你確切的問題,但顯然如果你在同一頁面上有兩個表單,你將不得不適當地修改我的例子。我可以給你的最好建議是下載一些體面的devtools(Firebug,Chrome DevTools等),閱讀JS文檔和實驗。如果仍然無法正常工作,請在SO上發佈另一個關於相關細節的問題,您已經嘗試了代碼**以及任何調試器輸出,並且有人會引導您朝着正確的方向前進。 – Xophmeister

+1

我確實發現了這個問題。謝謝你的幫助。 – user1400854

1

有許多不同的方式去了解這一點,但一個簡單的方法是硬編碼在HTML初始狀態,然後用javascript在需要時將其覆蓋。

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

嗯,我剛剛做到了。但縣選項的其餘部分仍然顯示。我如何覆蓋和什麼?對不起真的不熟悉JavaScript。 – user1400854

+1

查看Hakan Hastekin和Xophmeister for JavaScript和jQuery實現的答案。請注意,Hakan的解決方案實際上不需要jQuery。 Xophmeister推薦閱讀jQuery API。此外,他們[文檔](http://docs.jquery.com/)頁面中的「入門」部分對初學者很友好。另一個建議是,如果您對JavaScript不熟悉,請首先閱讀教程或介紹。 jQuery是用JavaScript編寫的,所以如果你從對JavaScript的基本理解開始,那麼jQuery將會更有意義。 –

1

在這裏,你去了,還添加了一些評論。測試工作。

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