JS Province City Two-level dynamic linkage example

Source: Internet
Author: User

<! DOCTYPE html>


<meta charset= "UTF-8" >
<title>Title</title>

<body>
<select id= "province" onchange= "Func1 (this)" ></select>
<select id= "City" ></select>
<script>
data={"Anhui": ["Ma On Shan", "Hefei", "Wuhu", "Tongling", "Bengbu"], "Jiangsu": ["Nanjing", "Suzhou", "Wuxi", "Changzhou", "Nantong"], "Shandong": ["Jinan", "Qingdao", "Jimo", "Penglai", "Taizhou"]};
var Pro=document.getelementbyid ("province"); Locate the label object for the province
var Cit=document.getelementbyid ("City"); Find the Label object of the city

For (var k in data) {//Traversal data data K is key province name
var opt=document.createelement ("option"); Create label for option
Pro.appendchild (opt); Add the option label created to the province
opt.innerhtml=k; Add the text of the K key to the tag
}

function func1 (EV) {
cit.options.length=0; Here's the trick of using options.length=0 to empty the option added after each click
for (var i in Data[ev.value]) {//This.value is the key value in the original province
var op=document.createelement ("option"); Create label for option

cit.appendchild (OP); Add the option created
Op.innerhtml=data[ev.value][i]; Note: I is not the content of the key data is the index cannot be directly =i
}
}

</script>
</body>
================== Note: Here is not directly in the HTML to write dead static code, because if the data added and modification will be cumbersome, with the JS statement control only need to modify data ======================== ==

PS: The process of learning is a bit of accumulation, not smart can be successful!

Js Province City Two-level dynamic linkage example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.