2017-03-16 49 views
1

我是jQuery的新手,並且遇到了無法發佈源自依賴動態下拉列表的值的問題。我不能張貼從動態依賴項下拉列表中的值

這是我寫的代碼:

的index.php

<form name="form1" action="test.php" method="post"> 
<table> 
    <tr> 
     <td> 
      <select id="branddd" onchange="change_brand()" required> 
       <option disabled="disabled" selected="selected" style="color:gray" required >brand</option> 
       <?php  
       $res=mysqli_query($link,"select * from brand"); 
       while($row=mysqli_fetch_array($res)) 
       { 
       ?> 
       <option name="brand" value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option> 
       <?php 
       } 
       ?> 
      </select> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <div id="model"> 
      <select name="model"> 
       <option required>model</option> 
      </select> 
     </td> 
    </tr> 
    <tr> 
     <td><input type="submit" value="submit"></td> 
    </tr> 
</table> 

這是我寫從MySQL數據加載到第二個下拉框中的JavaScript:

<script type="text/javascript"> 
function change_brand() 
{ 

    var xmlhttp=new XMLHttpRequest() ; 
    xmlhttp.open("GET","ajax.php? brand="+document.getElementById("branddd").value,false) ; 
    xmlhttp.send(null) ; 
    document.getElementById("model").innerHTML=xmlhttp.responseText ; 

} 
</script> 

ajax.php

<?php 
    $link=mysqli_connect("localhost","root",""); 
    mysqli_select_db($link,"test_db"); 
    $brand=$_GET["brand"]; 

    if($brand!="") 
    { 
     $res=mysqli_query($link,"select * from model where brand_id=$brand"); 
     echo "<select>"; 
     while($row=mysqli_fetch_array($res)) 
     { 
      echo "<option>"; echo $row["name"]; echo "</option>"; 
     } 
     echo "</select>"; 
    } 
?> 
+0

你說你正在嘗試POST,但你正在使用GET。要使用jquery進行POST,你可以使用[$ .post](https://api.jquery.com/jquery.post/) – user2896976

+0

你必須有你的第一個選擇名稱 – yogesh84

+0

謝謝我忘了我只是添加它,但我得到id值然後名字值 – Mouhssine

回答

1

添加名稱屬性,在select[id="branddd"]而不是像options添加name="brand"select tag

​​

檢查你的div被關閉後,您select[name="model"]。而添加required到選擇框而不是它的option

而且在服務器端,你需要不呼應<select>再次嘗試此而已,

while($row=mysqli_fetch_array($res)) 
{ 
    echo "<option>".$row["name"]."</option>"; 
} 

並添加id來select而不是div

如果你正在使用jQuery那麼你的onchange事件可以做空像,

$(function(){ 
    $('#branddd').on('change',function(){ 
     this.value && // if value!="" then call ajax 
      $.get('ajax.php',{brand:this.value},function(response){ 
      $('select[name="model"]').html(response); 
     }); 
    }); 
}); 

使用jQuery的情況下,你必須需要從<select id="branddd" onchange="change_brand()" required>刪除onchange,並會成爲像<select id="branddd" required>

+0

謝謝當我嘗試第一個建議,我從我的表單行動第二下拉值得到的價值,但不是從第一個 – Mouhssine

+0

嘗試我更新的答案,並在'品牌選擇框'中添加'name'。它會解決你的問題。 –

+0

感謝您的努力,我只是做了它,但它給了我的品牌「ID」不是「名稱」,所以即時試圖呼應品牌「名稱」我隱藏,看看我是否可以解決它 – Mouhssine