简体   繁体   中英

Populate Select based on another Select

I'm trying to populate a Select Box based in the choice of the first Select Box, but I'm having some troubles doing it. Simply nothing happens.

What I have until now (this is on my footer):

<script src="./plugins/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.category").change(function(){
    var selectedCategory = $(".category option:selected").val();
    $.ajax({
        type: "POST",
        url: "../inc/get_subcat.php",
        data: { category : selectedCategory } 
    }).done(function(data){
        $("#subcategory").html(data);
    });
});
});
</script>

The page with the div is located at /pages/file.php:

     <div class="col-md-6">
     <div class="form-group">
     <label class="control-label">SubCategory</label>
     <div id="subcategory"> </div>
 </div>                                      </div>

The file that does the query is in another folder (inc/get_subcat.php):

<?php
include("config.php");

if(isset($_POST['category'])){
$cat = validar($_POST['category']);

$query = "SELECT id, subcategory FROM subcategories WHERE catid = ?";
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
    echo "<select class='form-control' id='subcategory' name='subcategory'>";
    # Save in $row_data[] all columns of query
    while($row_data = $stmt_result->fetch_assoc()) {
    # Action to do
        echo "<option value='$row_data[id]'>$row_data[category]</option>";
    }
    echo "</select>";
}
$stmt->close();
}
?>

There is someone that could help me trying to fix this error? Can't fix despite trying for some hours.

Thanks!

Edit: This is the HTML code with all Select Box:

                                            <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label class="control-label">Category</label>
                                                    <select class='form-control' id='category' name='category'><option value='1'>Categoria 1</option><option value='2'>Categoria 2</option></select>                                                    </div>                                          

                                        </div>
                                            <div class="col-md-6" id="subcategory">

                                            </div>
                                        </div>

In your HTML you have <select class='form-control' ...etc

So the <select> has a class "form-control" only.

But your selector is $("select.category").change ...etc. which means it's looking for a select with "category" in the class attribute (the dot . in the selector signifies a class). Such an element doesn't exist, hence why nothing happens.

Perhaps you meant to use the ID (in which case $("#category").change ...etc)? Either that or you need to write <select class='form-control category' ...etc before it will work.

May be problem in your array data or query. So please check it first. I post here working example of depending drop down may be this will help you.

PHP code

$sub_category // Your array of Subcategory;
if ($sub_category) {
            echo '<option value="">Sub Category</option>';
            foreach ($sub_category as $sub_category) {
                $selected = '';
                if($sub_category['sub_category_id'] == $data['product']['sub_category_id'])
                {
                    $selected = 'selected';
                }
                echo '<option value="' . $sub_category['sub_category_id'] . '" '.$selected.'>' . $sub_category['sub_category'] . '</option>';
            }

        }

JS code

<script type="text/javascript">

   loadSubCategory();

    jQuery(document).ready(function($) {

        $(document).on('change', '.category_id', function(event) {
            event.preventDefault();

            loadSubCategory();
        });

    });

    function loadSubCategory()
    {
           var category_id = $(".category_id option:selected").val();

            $.ajax({
                url: 'Your Path Of server Function',
                type: 'post',
                data: {category_id: category_id, product_id : "<?= $product['product_id']?>" },
                cache: false,
                success: function (resp) {
                    if(resp)
                    {
                        $('.sub_category_id').html(resp);
                    } else {
                        $('.sub_category_id').html('<option value="">Sub Category</option>');
                    }

                }
            })
    }
</script>

HTML Code

<div class="form-group">
                        <b>Product Category </b> 
                        <select class="form-control category_id" id="category_id" name="category_id">
                            <option>Category</option>
                        <?php 

                            <option value="<?= $value['category_id'] ?>"  <?=$selected ?> ><?= $value['category'] ?></option>

                        </select>
                    </div>
                    <!-- Category End -->
                     <!-- Sub Category Start -->
                    <div class="form-group">
                        <b>Product Sub Category </b> 
                        <select class="form-control sub_category_id" name="sub_category_id">
                            <option value="">Sub Category</option>
                <option value="">Sub Category</option>
                 <option value="20">Books Stationery</option>
                                  <option value="21">Gaming and Accessories</option>
                                  <option value="22">Music Musical Instruments</option>

                        </select>
                    </div>

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