2016-04-22 75 views
0

我需要幫助解決這個問題。 我想做一個動態下拉菜單,當我從一個下拉菜單中選擇一個值到「A」時,另一個下拉菜單將被設置爲「B」。Dropdown自動選擇一個值

我有一個像這樣動態下拉的javascript函數。

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

我認爲你必須缺少代碼,因爲沒有提及你發佈的內容。 – Goose

+0

你能不能發佈你的所有相關代碼 – webGautam

+0

我還沒有做出下拉功能。但是,這是我的動態函數 –

回答

0

參考:how to dynamically change item of two related combobox

在短:

  1. file1.php,檢索的MySQL tbl1和在組合框中顯示它。
  2. 在組合框的變化,取選項的值和通過AJAX它傳遞一個PHP文件file2.php並顯示輸出在由file2.php產生file1.php
  3. file2.php,檢索mysql tbl2與Id通過Ajax並生成組合框B

實施例:

的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 
} 
?> 

注:

使用的mysqli或PDO來代替mysql的

下面演示和下載都是基於陣列,可以使用mysqli的檢索工具。

也可以嘗試使用$ .ajax,這也更容易。

DEMO | DOWNLOAD

+0

但我不需要使用數據庫。我只使用2個選項,即A和B選項。然後如果我選擇A,其他下拉列表將被選中B –

+0

您是否在使用數組 –

相關問題