How to make the select complete based on the selected variable in another select

0

I need to make sure that after choosing the product, in the quantity selection, display a list with the values according to the quantity available, for example: if you have 10 pieces of a trouser, display values from 1 to 10 in the select field automatically.

    <form name="products" id="products" method ="post" action ="registering_request.php">
        <fieldset style = "width: 640px; height: 640px; margin: 0px auto; border-size = 0px;"><legend align ="center"><h2>Novo Pedido</h2></legend> 
        <br>    
        <select name="CmbCustomers" id="CmbCustomers"> 
        <option value="">Selecione o Cliente</option>
        <?php
        $query_cust = "SELECT 'name' FROM customers";
        $select_customers = $PDO->prepare($query_cust);
        $select_customers->execute();

        //Conta a quantidade de linhas de clientes no BD;
        $number_of_rows_cust = $select_customers->rowCount();

        //Pega os dados dos clientes no BD; 
        $data_cust = $select_customers->fetch();

        //Verifica se a quantidade de linhas de clientes no BD é maior que 0; 
        if ($number_of_rows_cust > 0){
            echo '<option value="'.$data_cust['name'].'">'.$data_cust['name'].'</option>';
            } else {
            echo '<option value="">Sem clientes cadastrados</option>';
        }
        ?>
        </select>
        </p>
        <select name="CmbProd1" id="CmbProd1">
        <option value=""> Selecione o Produto </option>
        <?php
        $query_prod1 = "SELECT 'name', 'id' FROM 'products'";
        $select_product1 = $PDO->prepare($query_prod1);
        $select_product1->execute();

        //Conta quantas linhas tem no banco de dados; 
        $number_of_rows_prod1 = $select_product1->rowCount();

        //Pega o conteudo do banco de dados;
        $data_prod1 = $select_product1->fetch();

        //Preenche o campo option com o conteudo do BD;
        if ($number_of_rows_prod1 > 0){
            echo '<option value="'.$data_prod1['id'].'">'.$data_prod1['name'].'</option>';
            } else {
            echo '<option value="">Sem produtos disponíveis</option>';
        }
        ?>
        </select>
        <select id="CmbQuantProd1" style="display:none"></select>
        <script>
            $("#CmbProd1").on("change",function(){
                var id_product = $("#CmbProd1").val();
                $.ajax({
                    url: "verifyQuantity.php",
                    type: "POST",
                    data:{id_product:id_product},
                    beforeSend: function(){
                        $("#CmbQuantProd1").css({"display":"block"});
                        $("#CmbQuantProd1").html("Carregando...");
                        },
                        success: function(data)
                        {
                            $("#CmbQuantProd1").css({"display":"block"});
                            $("#CmbQuantProd1").html(data);
                        },
                        error: function(data)
                        {
                            $("#CmbQuantProd1").css({"display":"block"});
                            $("#CmbQuantProd1").html("Houve um erro ao carregar");
                        }
                    });
            });
        </script>
        </p><br><br><br>
        <center>
        <button type="submit" name="salvar" value="salvar" class="bVerde">Registrar</button> &nbsp &nbsp <button type="button" name="voltar" value="main.php" class="bCinza" onclick="window.location='main.php';">Voltar</button></p>
        </center>   
        </div>
    </body>

And in verifyQuantity.php:

    <?php
    include 'conexao.php';
        $sql = $conn->prepare("SELECT * FROM stock WHERE id_product = '".$_POST['id_product']."'");
        $sql->execute();
        $fetchAll = $sql->fetchAll();
        foreach($fetchAll as $result)
        {
            echo '<option value="'.$result['quantity'].'">'.$result['quantity'].'</option>';
        }
    ?>

That's how it worked.

    
asked by anonymous 19.02.2018 / 20:20

1 answer

0

You have to make a query via ajax to fill the second <select> Start by downloading jquery and instantiating in your project, then open tag script with the following code:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><formname="products" id="products" method ="post" action ="registering_request.php">
    <fieldset style = "width: 65%; margin: 0px auto; border-size = 10;"><legend align ="center"><h2>Novo Pedido</h2></legend>
        <br>
        <select name="CmbCustomers">
            <?php
            include "conexao.php";
            foreach($conn->query('SELECT name FROM customers ORDER BY name ASC') as $row){
                echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
            }
            ?>
        </select>
        </p>
        <select name="Cmb_Prod1">
            <?php
                foreach($conn->query('SELECT name, price FROM products ORDER BY name ASC') as $row) {
                    echo '<option value="' . $row['name'] . '">' . $row['name'] . '</option>';
                }?>
        </select>
        <select name="Cmb_QuantProd1">
            <!-- <option value="">Quantidade</option> -->
        </select>
        </p>
        </p>
        </div>
        <center>
            <button type="submit" name="salvar" value="salvar" class="bVerde">Registrar Pedido</button>
            &nbsp &nbsp <button type="button" name="voltar" value="main.php" class="bCinza" onclick="window.location='main.php';">Voltar</button></p>
        </center>
    </fieldset>
</form>

<script>
    $(document).ready(function(){
        $('select[name="Cmb_Prod1"]').on('change', function() {
            var value = $(this).val();
            $.ajax({
                url: 'verifyQuantity.php',
                data: {
                    value: value
                },
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    var html = '';
                    $.each(data, function () {
                        html+= '<option value="'+this.id+'">'+this.name+'</option>';
                    });

                    $('select[name="Cmb_QuantProd1"]').html(html);
                }
            });
        })
    })
</script>

link to jquery download: link

    
23.02.2018 / 19:34