How to get select to be populated based on the variable selected in another select

Asked

Viewed 341 times

0

I need to make that after choosing the product, in the quantity select display a list with the values according to the available quantity, for example: if you have 10 pieces of a pants, display the 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 way it worked.

  • The amount ta saved in the databank, and Voce wants a select with that amount according to the product’s select, that’s it ?

  • Is willing to use only php or is open to jquery?

  • @Anthraxisbr yes, the available quantity is in the Mysql database

  • @I_lile_trains If Jquery solve this I want to learn yes :D

1 answer

0

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

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<form name="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>

jquery download link: http://jquery.com/download/

  • I set some things in the code by following what you said, but in the php error logs it appears that the value is not set even I selecting the product before, can you please check? I updated the code upstairs

  • I made an adjustment to my answer, but let’s go to a few points, you don’t need to include the verifyQuantity file, if not php will call it face, and see that there really is no property value. Another point is at the beginning of the file add the script tag importing jquery: <script type="text/javascript" src="jquery-3.3.1.min.js"></script> At the end of the file open another tag script with the same code that is in my answer, do not need to put between the tag select

  • I made some adjustments following an example I found on the internet and it worked, thanks for the help Arlllon ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.