<select name="select8" size="1">
<option selected>选择省份</option></select>
<select name="select8" size="1">
<option selected>选择城市</option>
</select>
我想用以上这两条语句放在一个提交的表单中,当选择省份后,第二个要选择城市中会自动出现与其选择的省份相对应的城市,这样的代码如何写思路是什么?
谢谢!
<option selected>选择省份</option></select>
<select name="select8" size="1">
<option selected>选择城市</option>
</select>
我想用以上这两条语句放在一个提交的表单中,当选择省份后,第二个要选择城市中会自动出现与其选择的省份相对应的城市,这样的代码如何写思路是什么?
谢谢!
有二种实现方式,一种是纯javascript,将省份与城市关系定义成数组,这样省份加上onchange事件,对应一个事件,这个事件完成城市的select的重新构造.
另一种方式当省份触发onchage事件时,在对应的事件里用ajax实时向后台PHP请求当前省份对应的城市,后台返回城市列表,然后重新构造select其实实现过程是一致的,只不过获取数据的方式不同,一个是从javascript数组获取,一是通过ajax从后台实时获取.
function $(id)
{
return document.getElementById(id);
}
function getCity()
{
var cityArray = new Array();
cityArray['北京'] = ['朝阳区','海淀区','丰台区','通州'];
cityArray['天津'] = ['天津','天津'];
cityArray['河南'] = ['郑州','漯河','信阳'];
cityArray['河北'] = ['石家庄','石家庄'];
//alert(cityArray[$('sel8Id').options[$('sel8Id').selectedIndex.value]]);
///*var count =*/ alert(cityArray["'" + $('sel8Id').options[$('sel8Id').selectedIndex].value + "'"].length);
//alert(cityArray[$('sel8Id').options[$('sel8Id').selectedIndex].value].length);
var sel9Val = $('sel8Id').options[$('sel8Id').selectedIndex].value;
var count = cityArray[sel9Val].length;
$('sel9Id').options.length = count + 1;
for(var i=1;i<=count;i++)
{
$('sel9Id').options[i] = new Option(cityArray[sel9Val][(i-1)],cityArray[sel9Val][(i-1)]); }
}</script>
<select id="sel8Id" name="select8" size="1" onchange="getCity();">
<option selected>选择省份 </option>
<option value="北京">北京</option>
<option value="天津">天津</option>
<option value="河南">河南</option>
<option value="河北">河北</option>
</select>
<select id='sel9Id' name="select9" size="1">
<option selected>选择城市 </option>
</select>
给出了一个简单的提示,其实最好可以利用ajax动态的从数据库读取省份对应的城市