How to populate second dropdown list based on the first one

How to populate second dropdown list based on the first one

Hello,

I am having a real problem.....

I have 2 dropdown list that are dynamically populated via php, I am struggling populating the second dropdown list based on the first dropdownlist choice.


Here is my code:
  1.                         <select name="<?php echo "action".++$action_id; ?>" class="form-control products" id="<?php echo "products".++$products_id; ?>">
                            <?php
                            $query_field3 = "SELECT * FROM products ORDER BY name desc";
                            $result_field3 = mysqli_query($connection, $query_field3) or die (mysqli_error());
                            while($row_field3 = mysqli_fetch_array($result_field3)){
                            $product_name = htmlspecialchars($row_field3['name']);
                            $product_price1 =  htmlspecialchars($row_field3['price1']);
                            $product_price2 =  htmlspecialchars($row_field3['price2']);
                            $product_price3 = htmlspecialchars($row_field3['price3']);
                            ?>
                            <option value="<?php echo $product_name; ?>" data-product_price1="<?php echo $product_price1; ?>" data-product_price2="<?php echo $product_price2; ?>" data-product_price3="<?php echo $product_price3; ?>"><?php echo $product_name; ?></option>
                            <?php } ?>
                            </select>

                            <!--Price Select-->
                            <select name="<?php echo "action".++$number2; ?>" class="form-control prices">

                            <option id="price1"></option>
                            <option id="price2"></option>
                            <option id="price3"></option>
                           
                                            </select>

And here my jqeury but it does not work, what am I doing wrong please? Remember the ids are also dynamic(this is why I tried to use classes instead).

  1. <script>   
    $(document).ready(function () {   
        var allOptions = $('.form-control.prices option')
        $('.form-control.products').change(function () {
            $('.form-control.prices option').remove()
            var classN = $('.form-control.products option:selected').prop('class');
            var opts = allOptions.filter('.' + classN);
            $.each(opts, function (i, j) {
                $(j).appendTo('.form-control.prices');
            });
        });
    });
    </script>

I am very new to Jquery....

Thank you in advance for your help.

Ben