js realizes the effect of provincial drop down menu

  • 2021-07-21 07:11:21
  • OfStack

Two drop-down boxes. After selecting the Level 1 menu, the corresponding alternatives appear in the Level 2 menu. You cannot submit if you have no choice.

Create the html file first


<!DOCTYPE html>
<html>
<head>
 <title></title>
</head>
<body>
 <form>
  <select id="province">
   <option selected="selected"> Please select ...</option>
  </select>
  <select id="city">
   <option selected="selected"> Please select ...</option>
  </select>
  <button type="submit" id="where_submit" disabled="disabled"> Submit </button>
 </form>
</body>
<script type="text/javascript">
var provinces=[' Liaoning ',' Beijing ',' Shanghai ',' Jilin ',' Zhejiang '];
// The newly added provinces are at the top 
var choice=[' Please select ...']
var zhejiang=[' Hangzhou ',' Jiaxing ',' Ningbo ',' Shaoxing '];
var shanghai=[' Jinshan ',' Zhabei ',' Putuo ',' Xuhui '];
var jilin=[' Changchun ',' Liaoyuan ',' Jilin ','4 Flat '];
var beijing=[' Haidian ',' Sunrise ',' East Side ',' West City '];
var liaoning=[' Shenyang ',' Dalian ',' Panjin ',' Jinzhou ',' Liaoyang ',' Anshan ']
// Cities are ranked from back to front 
var citys=new Array;
citys[0]=choice;
citys[1]=zhejiang;
citys[2]=jilin;
citys[3]=shanghai;
citys[4]=beijing;
citys[5]=liaoning;


function add_option(select,option){
 var target=document.getElementById(select);
 for (var i = option.length - 1; i >= 0; i--) {
  var add_option=document.createElement("option");
  add_option.text=option[i];
  target.add(add_option,null);
  target.lastChild.setAttribute("name",option[i]);
 }

}
add_option("province",provinces);


document.getElementById("province").addEventListener("change",function(){


 var selevted_province=document.getElementById("province");
 var selected_city=document.getElementById("city");

 for (var i = selevted_province.length - 1; i >= 0; i--) {
  selected_city.remove(i);
 }
 var selected=selevted_province.selectedIndex;
 if (selected==0) {
  add_option("city",citys[0]);
  document.getElementById("where_submit").setAttribute("disabled","ture");
 }else{
  add_option("city",citys[selected]);
  document.getElementById("where_submit").removeAttribute("disabled");
 }
})
</script>
</html>

Related articles: