SoFunction
Updated on 2025-04-05

JavaScript realizes three-level linkage menu effect

The three-level linkage test should be the processing of data. As long as the relationship is clear, the more levels it will be the same:

html part:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <title>3Cascade linkage menu</title>
 <script>
 var region = {
  Guangdong:
  {
  "Guangzhou":["Guangzhou 1","Guangzhou 2","Guangzhou 3"],

  "Zhuhai":["Zhuhai 1","Zhuhai 2","Zhuhai 3"],

  "Foshan":["Foshan 1"]
  },
  Hunan:
  {
  "Changde":["Stone Gate","Peach Garden","Linli","Hanshou"],

  "Yiyang":["Yiyang 1","Yiyang 2","Yiyang 3"]
  }
 }
 </script>
</head>
 <body>

 <select  onchange="change();">
  <option>Please select a province</option>
 </select>

 <select  onchange="countyChange();">
  <option>Please choose a city</option>
 </select>

 <select >
  <option>Please select a county town</option>
 </select>
 <script src=''></script>
 </body>
</html>

js part:

var province = ("#province");
 var city = ("#city");
 var county = ("#county");
 //The second-level linkage does not need to define the province you choose, but directly use the province (key) to determine the following city value (value) value var provinceName = null;

 for (ele in region){
 var op = new Option(ele , ele , false , false); //new Option("text","value",true,true). The next two true means that the default is selected and valid respectively //(op);
 [] = op;
 }

 var change = function(src){
  = "";
 if(src === 'Please select a province'){
  var op = new Option('Please select a city' , 'Please select a city' , false , false);
  [0] = op;
 }else{
  for (index in region[src]){
  //(index);
  var op = new Option(index , index , false , false);
  [] = op;
  }
 }
 //Remember to select the value of the province provinceName=src;
 countyChange()
 }

 var countyChange = function(src2){
  = "";
 if(src2 === 'Please select a city'){
  var op = new Option('Please select the county town','Please select the county town', false , false);
  [0] = op;
 }else{
  for (index in region[provinceName][src2]){
  //(index);
  var op = new Option(region[provinceName][src2][index] , region[provinceName][src2][index] , false , false);
  [] = op;
  }
 }
 }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.