下拉菜单自动选择一个值

i need help for this problem. I want to make a dynamically dropdown and when i select a value from one dropdown to "A", the another dropdown will be set to "B".

I have a javascript function for dynamically dropdown like this.

<script type="text/javascript">
function coba(){
        document.getElementById("add").innerHTML +=
  " <inputclass='department_name' type='text' 
   size='50' />";
  }
 </script>

REFERENCE: how to dynamically change item of two related combobox

In Short:

  1. In file1.php, Retrieve mysql tbl1 and display it in a combo box A.
  2. On change of Combo box A, Fetch the value of option and pass it a php file file2.php via ajax and Display the output in file1.php which is produced by file2.php.
  3. In file2.php, Retrieve mysql tbl2 with the Id passed by Ajax and generate a combo box B.

Example:

index.php

<script type="text/javascript">
function GetXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }   
    return null;
}

function ajax_function(url, postData, id)
{
    xmlhttp=GetXmlHttpObject();
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", postData.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4)
        {
            document.getElementById(id).innerHTML=xmlhttp.responseText;                            
        }       
    }                
        xmlhttp.send(postData);
}

function dispSecond(Id)
{
    var params  = 'Id=' + Id ;
    var DivId = 'dispDiv';
    ajax_function('ajax_display.php', params, DivId);
}

</script>

<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
   Example:  $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>

<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';  
}
?>
</select>

<div id="dispDiv"></div>

ajax_display.php

<?php
$Id     = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
   Example:  
   If $Id=1 
   $SubArray = array(1=>'Focus',2=>'Explorer');
   If $Id=2
   $SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
    <select id="drop_second" name="drop_second">
    <option value="0">[Select]</option>
    <?php
    foreach ($SubArray as $k=>$v)
    {
    echo '<option value="'.$k.'">'.$v.'</option>';  
    }
    ?>
    </select>
<?php
}
?>

Note:

Use Mysqli or PDO instead mysql

Below Demo and Download are based on arrays, you can implement by using mysqli retrieval.

Also You can try using $.ajax which is more easy also.

DEMO | DOWNLOAD