简体   繁体   中英

Populating drop down list

I am have three drop down list : Country , State and City.

I want to populate state list based on selection in country list and populate city list based on selection in state list.

Here's how I have attempted this

  1. From the country list, using the onchage event I call java script function.

     <select name="country" id="id1" onchange="onCountryChange(this.value)"> 
  2. Then I send a request to server to get names of states associated with country.

     function onCountryChange(str){ if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("statenames").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","./view/countrychange.php?countryname="+str,true); xmlhttp.send(); } 
  3. The I get the values of states using the following code.

     <?php $countryname=$_GET["countryname"]; $connection = pg_connect("host=localhost port=5432 dbname=STAGE2 user=postgres password=jssate"); if (!$connection){ echo "<H1>Error in connection to Database</H1>"; echo "<H2>Please try again</H2>."; } else{ $query1="Select distinct(state) from master_table where country='$countryname'"; $result = pg_query($connection,$query1); $numrows = pg_numrows($result); if ($numrows>0){ echo "State <select name="state" id="stateid">; for ($row_index=0;$row_index<$numrows;$row_index++) { $state_name=pg_result($result,$row_index,0); echo "<option value="$state_name\\">$state_name</option>"; } echo "</select>"; } } pg_close($connection); ?> 

3 .Used the following code on my client side to display the result.

    <div id="statenames">
    //Original select list placed here is replaced by the one returned by server.
    </div>

This does work for me and the states are populated based on country name. Now how do I populate the third list. Is the approach I have chosen for displaying the state list correct? As I have no control on the select list of state which I get now.

Create 3 select country, city and state selects in your html page

  • only country select element will have option, state and city will be empty.
  • on change event of country send and ajax request to fetch state, and as the response send only option elements DO NOT WRAP THEM IN A SELECT as you have done
  • Push these options into state's select element

    document.getElementById('state').innerHTML(state_ajax_response);

Then create function in your html file that will be called on the state select change and again repeat the procedure for the cities select

Hope you get it.

Just send option elements as response.

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