Soy nuevo en jQuery y tengo un problema en el que no puedo publicar un valor que se originó en una lista desplegable dinámica dependiente.
Aquí está el código que he escrito:
índice.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>Aquí está el JavaScript que he escrito para cargar datos de MySQL en el segundo cuadro desplegable:
<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>"; } ?>Agregue el atributo de nombre en su select[id="branddd"] y agregue name="brand" para select tag que no está en options como,
<select id="branddd" name="brand" ... Verifique que su div esté cerrado después de su select[name="model"] . Y agregue required al cuadro de selección en lugar de su option
Y al final del servidor, no necesita repetir <select> nuevamente, intente esto solo,
while($row=mysqli_fetch_array($res)) { echo "<option>".$row["name"]."</option>"; } Y agregue id para select en lugar de div
Y si está utilizando jquery, su evento onchange puede ser corto como,
$(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); }); }); }); En caso de usar jquery, debe eliminar onchange de <select id="branddd" onchange="change_brand()" required> y sería como <select id="branddd" required>