html中select控件(省份与城市关联)
Javawe中htmlselect关联
html代码:
<select id="province" runat="server" onchange="selectprovince(this);" style=" width:95px;"></select>
<select id="city" runat="server" style=" width:95px;"></select>
javascript代码:
<script type="text/javascript">
var list1 = new Array;
var list2 = new Array;
list1[list1.length] = "北京市";
list1[list1.length] = "天津市";
list1[list1.length] = "其它";
list2[list2.length] = new Array("北京", "东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区", " 海淀区(中关村)", "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "怀柔区", "平谷区", "密云县", "延庆县", " 其他");
list2[list2.length] = new Array("和平区", "河东区", "河西区", "南开区", "红桥区", "塘沽区", "汉沽区", "大港区",
"西青区", "津南区", "武清区", "蓟县", "宁河县", "静海县", "其他");
var ddlProvince = document.getElementById("province");
var ddlCity = document.getElementById("city");
for(var i =0;i<list1.length; i++)
{
var option = document.createElement("option");
option.appendChild(document.createTextNode(list1[i]));
option.value = list1[i];
ddlProvince.appendChild(option);
//city initialize
var firstprovince = list2[0];
for (var j = 0; j < firstprovince.length; j++) {
var optioncity = document.createElement("option");
optioncity.appendChild(document.createTextNode(firstprovince[j]));
optioncity.value = firstprovince[j];
ddlCity.appendChild(optioncity);
}
}
function indexof(obj,value)
{
var k=0;
for(;k<obj.length;k++)
{
if(obj[k] == value)
return k;
}
return k;
}
function selectprovince(obj) {
ddlCity.options.length = 0;//clear
var index = indexof(list1,obj.value);
var list2element = list2[index];
for(var i =0;i<list2element.length; i++)
{
var option = document.createElement("option");
option.appendChild(document.createTextNode(list2element[i]));
option.value = list2element[i];
ddlCity.appendChild(option);
}
}
</script>
本文介绍了如何在HTML中使用select元素实现省市区的关联选择,结合Java后端和JavaScript前端代码来完成动态加载和联动效果。
2925

被折叠的 条评论
为什么被折叠?



