我想爲國家和城市創建級聯下拉菜單。我也想填充城市下拉列表,到目前爲止國家和州都沒問題,我錯過了什麼? 這是我走到這一步:國家/州/市依賴人選擇json&jquery
<form id="dropdowns" action="index.html">
<label>Country:</label>
<select id="country" name="country">
<option value="000">-Select Country-</option>
</select>
<br />
<label>State:</label>
<select id="state" name="network">
<option value="000">-Select State-</option>
</select>
<br />
<label>City:</label>
<select id="model" name="model">
<option value="000">-Select City-</option>
</select>
<br />
</form>
這是我使用的測試目的是什麼:
var myJson = {
"country": [
{
"name": "United States",
"id": "usa",
"states": [
{
"name": "State 1 USA",
"id": "usaState1",
"cities": [
{
"name": "City 1",
"id": "usaState1City1",
"area": "12345 sqkm"
},
{
"name": "City 2",
"id": "usaState1City2",
"area": "12345 sqkm"
}
]
},
{
"name": "State 2 USA",
"id": "usaState2",
"cities": [
{
"name": "City 3",
"id": "usaState2City3",
"area": "12345 sqkm"
},
{
"name": "City 4",
"id": "usaState2City4",
"area": "12345 sqkm"
}
]
}
]
},
{
"name": "Australia",
"id": "aus",
"states": [
{
"name": "State 1 Australia",
"id": "ausState1",
"cities": [
{
"name": "City 5",
"id": "ausState1City5",
"area": "12345 sqkm"
},
{
"name": "City 6",
"id": "ausState1City6",
"area": "12345 sqkm"
}
]
},
{
"name": "State 2 Australia",
"id": "ausState2",
"cities": [
{
"name": "City 7",
"id": "ausState2City7",
"area": "12345 sqkm"
},
{
"name": "City 8",
"id": "ausState2City8",
"area": "12345 sqkm"
}
]
}
]
}
]
}
這是jQuery腳本:
$.each(myJson.country, function (index, value) {
$("#country").append('<option value="'+value.id+'">'+value.name+'</option>');
});
$('#country').on('change', function(){
console.log($(this).val());
for(var i = 0; i < myJson.country.length; i++)
{
if(myJson.country[i].id == $(this).val())
{
$('#state').html('<option value="000">-Select State-</option>');
$.each(myJson.country[i].states, function (index, value) {
$("#state").append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
}
});
我可以沒有得到它的工作:
$('#state').on('change', function(){
console.log($(this).val());
for(var i = 0; i < myJson.country.length; i++)
{
if(myJson.country[i].states.id == $(this).val())
{
//console.log(myJson.country[i].states.id);
$('#model').html('<option value="000">Cities</option>');
$.each(myJson.country[i].states.cities, function (index, value) {
$("#model").append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
}
});
哪裏是你的'$(「#狀態」)。在('change''功能? – andi
是的,這裏是狀態改變事件? –
更新,我得到了什麼至今 – Santiago