简体   繁体   中英

how to create related dropdown lists for state and cities

i am trying to create a related dropdowns for cities and (related)state. here's is state.html

<html>
<head><script type= "text/javascript" src = "countries2.js"></script></head>
<body>
Select Country:   <select onchange="print_state('state',this.selectedIndex);" id="country" name ="country"></select>
            <br />
            City/District/State: <select name ="state" id ="state"></select>
            <script language="javascript">print_country("country");</script>

</body>
</html>

and states.js

var country_arr = new Array("Andaman & Nicobar ","Andhra pradesh","Arunachal Pradesh","maharashtra");

var s_a = new Array();
s_a[0]="";
s_a[1]="Nicobar|North and Middle Andaman|South Andaman";
s_a[2]=" Adilabad|Anantapur|Chittoor|East Godavari|Guntur|Hyderabad|Kadapa|Karimnagar|Khammam|Krishna|Kurnool|Mahabubnagar|Medak|Nalgonda|Nellore|Nizamabad|Prakasam|Rangareddy|Srikakulam|Visakhapatnam|Vizianagaram|Warangal|West Godavari";
s_a[3]="Anjaw|Changlang|Dibang Valley|East Kameng|East Siang|Kurung Kumey|Lohit|Lower Dibang Valley|Lower Subansiri|Papum Pare|Tawang|Tirap|Upper Siang|Upper Subansiri|West Kameng|West Siang";



function print_country(country_id){
    // given the id of the <select> tag as function argument, it inserts <option> tags
    var option_str = document.getElementById(country_id);
    var x, i=0;
    for(x in country_arr){
        option_str.options[i++] = new Option(country_arr[x],country_arr[x]);
    }
}

function print_state(state_id, state_index){
    var option_str = document.getElementById(state_id);
    var x, i=0; state_index++;
    var state_arr = s_a[state_index].split("|");
    for(x in state_arr){
            option_str.options[i++] = new Option(state_arr[x],state_arr[x]);
    }
}

when i try to select options, cities from previously selected state appear in the second dropdown box. how to avoid this??

Because you haven't remove the previously added cities from the "state_id" element. Hence in your print_state function after getting the id of the state element remove all its child and then proceed further. You can apply many methods for removing the child elements from the DOM node. One of the pure javascript way is as follows:

while(option_str.hasChildNodes()){
    option_str.removeChild(option_str.lastChild);
}

Again a more simple one liner method will be using the innerHTML property, if you can use this in your case:

option_str.innerHTML = "";     //will remove everything including the childs from the DOM node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM