简体   繁体   中英

How to populate a child drop down menu from parent selection PHP

How would one populate a child drop down selection on a static page from a parent drop down using only PHP. Eg having a child drop down populate with counties after you have selected which state you live in, or in my case populate series after manufacturer.

EDIT: Is there a way to do it without js?

<?php
$man = mysqli_query($con,"SELECT DISTINCT manufacturer FROM inventory.manufacturer WHERE manufacturer!=\"\" ORDER BY manufacturer;");               
echo "<select name=\"manufacturerS\">
<option value=\"\">Select</option>";
while($row = mysqli_fetch_array($man)) {
    echo "<option value=\"".$row['manufacturer']."\">".$row['manufacturer']."</option>";
}   
echo "</td>
<td>";

if(isset($_POST['manufacturerS'])){
$ser = mysqli_query($con,"SELECT DISTINCT series, manufacturer FROM inventory.audit WHERE series!=\"\" AND manufacturer='".$_POST['manufacturerS']."' ORDER BY series;");               
echo "<select name=\"seriesS\">
<option value=\"\">Select</option>";
while($row = mysqli_fetch_array($ser)) {
    echo "<option value=\"".$row['series']."\">".$row['series']."</option>";
}   
    echo "</td>
    <td>";      
}

You need of client-side to determine when manufacturerS select was selected, then you can use pure javascript :

<form id="manufacturerF" method="POST">
<select name="manufacturerS" onchange="document.getElementById('manufacturerF').submit();">
<?php  
    $man = mysqli_query($con, "SELECT DISTINCT manufacturer 
    FROM inventory.manufacturer 
    WHERE manufacturer!=\"\" 
    ORDER BY manufacturer;");

    while ($row = mysqli_fetch_array($man)) {
        echo '<option value="'.$row['manufacturer'].'>'.$row['manufacturer'].'</option>';
    } 
?>
</select>
</form>


<?php
    if(isset($_POST['manufacturerS']) && !empty($_POST['manufacturerS'])){  
        echo '<select name="seriesS">';

        $ser = mysqli_query($con,"SELECT DISTINCT series, manufacturer 
        FROM inventory.audit 
        WHERE series!=\"\" 
        AND manufacturer='".$_POST['manufacturerS']."' 
        ORDER BY series;");

        while ($row = mysqli_fetch_array($ser)) {
            echo '<option value="'.$row['series'].'">'.$row['series'].'</option>';
        }   

        echo '</select>';   
    }
?>

I recommend you use JQuery so will not need a <form> and reload your page. The correct idea would be to use JQUERY to detect when the select1 was selected and then with AJAX populate the select2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM