[英]How to create country list using array in javascript? i have total 10 or more select country box in page
[英]How to create an object array for a country list using html dom?
現在卡住了一段時間。 任何幫助,將不勝感激。
我正在為我的網站選擇一個帶有國家/地區選項的元素。 我有一個帶有2對象數組國家列表的javascript文件(我無法在html文件中指定選項,只能使用此js文件):
var country_list = [
{"country_code": "CA", "country_name": "Canada"},
{"country_code": "UK", "country_name": "United Kingdom"},
{"country_code": "AU", "country_name": "Australia"},
{"country_code": "NZ", "country_name": "New Zealand"} ];
然后這是我的html文件:
<form name="form1">
Country <select value="country_code" onclick="select_country()"></select>
</form>
國家名稱必須顯示在下拉列表中,而選項的值將是2個字母的國家/地區代碼。 另外,默認情況下必須選擇澳大利亞。
到目前為止,這是我一直在做的事情:
function select_country(){
var select = document.form1.createElement("SELECT");
select.setAttribute("id","mySelect");
document.form1.body.appendChild(select);
var option = document.form1.createElement("option");
option.setAttribute("value", "Canada");
var text = document.createTextNode("CAN");
option.appendChild(text);
document.form1.getElementById("mySelect").appendChild(option);
}
您可以使用vanilla js輕松完成此操作:
var selectElem = document.createElement("select");
for (var i = 0; i < country_list.length; i++) {
var option = document.createElement("option");
option.text = country_list[i].country_name;
option.value = country_list[i].country_code;
if (option.text == "Australia") option.selected = true; //default option
selectElem.appendChild(option);
}
document.form1.body.appendChild(selectElem);
for (i=0; i <=country_list.length; i++){
var select = document.form1.createElement("SELECT");
select.setAttribute("id","mySelect"+i);
document.form1.body.appendChild(select);
var option = document.form1.createElement("option");
option.setAttribute("value", country_list[i].country_name);
var text = document.createTextNode(country_list[i].country_code);
option.appendChild(text);
document.form1.getElementById("mySelect"+i).appendChild(option);
}
如果您想使用jQuery來做到這一點:
var country_list = [{
"country_code": "CA",
"country_name": "Canada"
}, {
"country_code": "UK",
"country_name": "United Kingdom"
}, {
"country_code": "AU",
"country_name": "Australia"
}, {
"country_code": "NZ",
"country_name": "New Zealand"
}]
.forEach(function(e){
$("<option value='"+ e.country_code+"'>"+e.country_name+"</option>")
.appendTo("select");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.