JS 实现下拉框 省市区三级联动
今天刚好做了以下表单验证,发现网上比较基础的三级联动教程并不多,所以我出此以本。
效果如图:
HTML代码如下:
1 <select name="province" onchange="getCity()"> 2 <option value="0">所在省</option> 3 <option value="直辖市">直辖市</option> 4 <option value="广东省">广东省</option> 5 <option value="江苏省">江苏省</option> 6 <option value="福建省">福建省</option> 7 </select> 8 <select name="city" onchange="getDistrict()"> 9 <option value="0">所在市</option> 10 </select> 11 <select class="clear-Mar" name="district"> 12 <option value="0">所在区</option> 13 </select>
JS代码如下:
1 var city=[ 2 ["北京市","天津市","上海市","重庆市"], 3 ["广州市","深圳市","珠海市","东莞市"], 4 ["南京市","苏州市","南通市","常州市"], 5 ["福州市","厦门市","莆田市","泉州市"] 6 ]; 7 var district=[ 8 [ 9 ["东城区","西城区","宣武区"],["和平区","红桥区","塘沽区"],["杨浦区","徐汇区"],["万州区","涪陵区"] 10 ], 11 [ 12 ["天河区","海珠区","白云区","番禺区"],["南山区","宝安区","福田区"],["香洲区","斗门区","金湾区"],["东城区","莞城区","万江区"] 13 ], 14 [ 15 ['玄武区','白下区','秦淮区','建邺区'],['沧浪区','平江区','金阊区','虎丘区'],['崇川区','港闸区','海安县','如东县'],['天宁区','钟楼区','新北区'] 16 ], 17 [ 18 ['鼓楼区','台江区','仓山区','马尾区'],['思明区','海沧区','湖里区','集美区'],['城厢区','涵江区','荔城区','秀屿区'],['鲤城区','丰泽区','洛江区','泉港区'] 19 ] 20 ]; 21 function getCity(){ 22 //获得省份下拉框的对象 23 var sltProvince=document.forms[0].province; 24 //获得城市下拉框的对象 25 var sltCity=document.forms[0].city; 26 //获得市区下拉框的对象 27 var sltDistrict=document.forms[0].district; 28 //得到对应省份的城市数组 29 var provinceCity=city[sltProvince.selectedIndex - 1]; 30 //清空城市下拉框,仅留提示选项 31 sltCity.length=1; 32 sltDistrict.length=1; 33 //将城市数组中的值填充到城市下拉框中 34 for(var i=0;i<provinceCity.length;i++){ 35 sltCity[i+1]=new Option(provinceCity[i],provinceCity[i]); 36 } 37 } 38 function getDistrict() { 39 var sltProvince=document.forms[0].province; 40 //获得城市下拉框的对象 41 var sltCity=document.forms[0].city; 42 //获得市区下拉框的对象 43 var sltDistrict=document.forms[0].district; 44 //得到对应城市的市区数组 45 var cityDistrict=district[sltProvince.selectedIndex - 1][sltCity.selectedIndex - 1]; 46 //清空城市下拉框,仅留提示选项 47 sltDistrict.length=1; 48 //将市区数组中的值填充到市区下拉框中 49 for(var i=0;i<cityDistrict.length;i++){ 50 sltDistrict[i+1]=new Option(cityDistrict[i],cityDistrict[i]); 51 } 52 }
CSS不是重点就不给出了,如有疑问可以在下方评论......