Home > Web Front-end > JS Tutorial > JavaScript method to implement province and city cascading drop-down boxes based on DOM

JavaScript method to implement province and city cascading drop-down boxes based on DOM

PHPz
Release: 2018-10-15 14:26:40
Original
1297 people have browsed it

This article mainly introduces the method of using JavaScript to implement province and city cascading drop-down boxes based on DOM. It can realize the function of selecting the corresponding city drop-down box after selecting a province. It is of great practical value. Friends who need it can refer to it

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>省市级联下拉框</title>
<script type="text/javascript">
var provs = { "江西省": ["南昌市", "景德镇", "九江", "鹰潭", "萍乡", "新馀", "赣州", "吉安", "宜春", "抚州", "上饶"],
  "福建省": ["福州", "厦门", "莆田", "三明", "泉州", "漳州", "南平", "龙岩", "宁德"],
  "河北省": ["石家庄", "邯郸", "邢台", "保定", "张家口", "承德", "廊坊", "唐山", "秦皇岛", "沧州", "衡水"]
};
function loadProv() {
  //加载省份数据
  var prov = document.getElementById("prov");
  for (var key in provs) {
    var provName = key;
    var optProv = document.createElement("option");
    optProv.value = provName;
    optProv.innerText = provName;
    prov.appendChild(optProv);
  }
}
function provChange() {
  var prov = document.getElementById("prov");
  var city = document.getElementById("city");
  var provName = prov.value;
  //如果没有选择省份,则把城市下拉框隐藏
  if (provName == "none") {
    city.style.display = "none";
    return;
  }
  else {
    city.style.display = "";
  }
  var citys = provs[provName];
  //city.options.length = 0;
  //用这种方法也可以清空原始列表
  //清空城市的原始数据
  for (var i = city.childNodes.length - 1; i >= 0; i--) {
    var child = city.childNodes[i];
    city.removeChild(child);
  }
  //添加新的城市数据
  for (var i = 0; i < citys.length; i++) {
    var optCity = document.createElement("option");
    optCity.value = citys[i];
    optCity.innerText = citys[i];
    city.appendChild(optCity);
  }
}
</script>
</head>
<body onload="loadProv()">
<select id="prov" onchange="provChange()">
<option value="none">请选择省</option>
</select>
<select id="city" style="display:none"></select>
</body>
</html>
Copy after login

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template