1
votes

I am a bit confused on my following problem.

In my current web based application i am having two dropdown.

 <select  name="country">
        <option value="">All</option>
        <option value="">India</option>
        <option value="">China</option>
 </select>

And

 <select  name="state">
        <option value="">All</option>
        <option value="">state1</option>
        <option value="">state2</option>
 </select>

Now what i need to do is, when ever i select India from country then second dropdown should show all the Indian state and when i choose china, it should show all chinese state in second dropdown.

I am using two tables for both country and state with following fields

Table country with columns: country_id, country_name

Table state with coulmn: state_id, country_id, state_name

I am storing the state name based on country_id in state table.

Please Suggest me.

2

2 Answers

2
votes
<td>Country</td>
<td>
      <select  id="country" onChange="getState(this.value)" name="country">
                            <option value="">All</option>
                            <option value="1">India</option>
                            <option value="2">China</option>

      </select>
</td>


function getState(str){
  if(str=='All'){
    document.getElementById("state").innerHTML="";     
  }else{
    document.getElementById("state").innerHTML="<img src='<?php echo $serverimage?>ajax-loader.gif' />";
        if(window.XMLHttpRequest){
            xmlhttp=new XMLHttpRequest();
    }
    else
    {
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
            if(xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("state").innerHTML=xmlhttp.responseText;
            }
    }
    xmlhttp.open("GET","state.php?countryid="+str,true);
    xmlhttp.send();
   }//ELSE ENDS
}//FUNCTION ENDS

//State.php

<?php
  $country=$_GET["country"];  
  /*
    code to fetch all states from database with $country and fetch in variable $states
    Fetch records based on value passed in country dropw down. ie id or countryname 
  */
    echo '<select name="state" id="state">';
   foreach($states as $state)                
     echo '<option value="'.$state.'">'.$state.'</option>';            

   echo '<option value="Other">Other</option>'; 
   echo '</select>';
   exit;    

?>

I have not tested this code so there could be some silly mistakes so take care of it.

0
votes