JavaScript 省市二級聯動
省市二級聯動,只需要傳入provsCitysMap的map集合,省市的id值即可。
<script type="text/javascript">
var provs = [
<c:forEach items="${provsCitysMap}" var="ps" varStatus="pi">
{ ctId:"${ps.key.cityId}",
ctName:"${ps.key.cityName }",
cities:[
<c:forEach var="cts" items="${ps.value }">
{
ctId:"${cts.cityId }",
ctName:"${cts.cityName }"
},
</c:forEach>
{}
],
},
</c:forEach>{}
];
var prov = document.getElementById('prov');
//新增省
for(var i = 0; i < provs.length-1; i++){
var op = new Option();
op.value = provs[i].ctId;
op.text = provs[i].ctName;
prov.options.add(op);
}
function toChangeCity(){
//取選中省的value
var provValue = document.getElementById("prov").value;
//獲取市列表的物件
var city = document.getElementById("city");
//清空市內容
for(var i = 0; i < city.options.length; ){
city.options.remove(0);
}
//以value取市的物件//新增到列表中
var selectProv = null;
for(var i = 0; i < provs.length; i++){
if(provValue == provs[i].ctId){
selectProv = provs[i];
}
}
for(var i = 0; i < selectProv.cities.length-1; i++){
var op = new Option();
op.value = selectProv.cities[i].ctId;
op.text = selectProv.cities[i].ctName;
city.options.add(op);
}
}
</script>