繁体   English   中英

根据第一个下拉列表选择填充 HTML/PHP 下拉列表

[英]Populate HTML/PHP Dropdown Based on First Dropdown Selection

我有 1 个用于类别(食物、饮料等)的下拉列表

在我的 MYSQL 表 (t_menu_category) 中,我有:

+----+---------------+-------------------+----------------------+
| ID | category_name | sub_category_name | category_description |
+----+---------------+-------------------+----------------------+
|  1 | Food          | Curries           | Spicy Curries        |
|  2 | Food          | Meat              | Lamb, Pork, Chicken  |
|  3 | Drinks        | Alcohol           | Fine Tasting Lager   |
|  4 | Desserts      | Cakes             | Chocolate Cake       |
+----+---------------+-------------------+----------------------+

我有第一个下拉列表显示“category_name”的值,但我想要的是当我选择食物时我希望第二个下拉框更新并只显示“sub_category_name”的值,例如第一个选择。 “食物”等于数据库中的“食物”。

所以如果我在第一个下拉框中选择了“食物”,第二个下拉框将只显示“咖喱”和“肉”。

HTML:

<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> 

    <p> 
        <label for="item_name">Item Name</label>
        <input id="item_name" name="item_name" required="required" type="text" placeholder="Item Name" />
     </p>
     <p>
        <label for="item_description">Item Description</label>
        <textarea rows="3" cols="100%" required="required" name="item_description">Item Description</textarea>
    </p>
    <p>
        <label for="item_category">Item Category</label>
        <select id="item_category" name="item_category" required="required">
            <option selected="selected">-- Select Category --</option>
            <?php 
            $sql = mysql_query("SELECT category_name FROM t_menu_category");
            while ($row = mysql_fetch_array($sql)){
            ?>

            <option value="<?php echo $row['category_name']; ?>"><?php echo $row['category_name']; ?></option>

            <?php
            // close while loop 
            }
            ?>
        </select>
    </p>

    <p class="center"><input class="submit" type="submit" name="submit" value="Add Menu Item"/></p>
</form>

任何帮助都将受到高度赞赏:)

您可以使用请求创建一个 PHP 文件并使用 AJAX 调用它。

getSubCategory.php

<?php
$category = "";
if(isset($_GET['category'])){
    $category = $_GET['category'];
}

/* Connect to the database, I'm using PDO but you could use mysqli */
$dsn = 'mysql:dbname=my_database;host=127.0.0.1';
$user = 'my_user';
$password = 'my_pass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$sql = 'SELECT sub_category_name as subCategory FROM t_menu_category WHERE category_name = :category';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':category', $category);
$stmt->execute();

return  json_encode($stmt->fetchAll());

并添加一些 jquery 以在选择类别时进行捕获,并向服务器询问相应的子类别:

<script>
    $(document).ready(function () {
        $('#item_category').on('change', function () {

            //get selected value from category drop down
            var category = $(this).val();

            //select subcategory drop down
            var selectSubCat = $('#item_sub_category');

            if ( category != -1 ) {

                // ask server for sub-categories
                $.getJSON( "getSubCategory.php?category="+category)
                .done(function( result) {    
                    // append each sub-category to second drop down   
                    $.each(result, function(item) {
                        selectSubCat.append($("<option />").val(item.subCategory).text(item.subCategory));
                    });
                    // enable sub-category drop down
                    selectSubCat.prop('disabled', false);                
                });

            } else {                
                // disable sub-category drop down
                selectSubCat.prop('disabled', 'disabled');
            }
        });    

    });
</script>

还要为您的第一个选项添加一个值:

<option value="-1" selected="selected">-- Select Category --</option>

我有一个简单的解决方案来根据国家/地区选择国家 php/javascript/mysql

MySQL表

country 
      country_code varhar(5)
      country_name varchar(100)

state
      country_code varhar(5)
      state_code   varchar(5)
      country_name varchar(100)

main.php 文件中的国家/地区选择

<html>
   <body> 
     Country
            <?php
                $sql="SELECT * FROM country order by country_name";
                $rs=$conn->Execute($sql);
                echo '<select  value="'.$country_code.'"  name="country_code"  id="country_list"   onChange="stateList(this.value);" />';
                echo  '<option value="">--Select--</option>';
                $rs->MoveFirst();
                while (!$rs->EOF) {
                    echo  '<option value="'.$rs->fields['country_code'].'"';
                    if  ($rs->fields['country_code'] == $country_code) {echo " selected";}
                    echo  '>'.$rs->fields['country_name'].'</option>';
                    $rs->MoveNext();
                }
                echo '</select>';
            ?>

     State
            <?php
                $sql="SELECT * FROM state where contry_code = '$country_code' order by state_name";
                $rs=$conn->Execute($sql);
                echo '<select   value="'.$state_code.'"  name="state_code" id="state_list"   />';
                echo  '<option value="">--Select--</option>';
                $rs->MoveFirst();
                while (!$rs->EOF) {
                    echo  '<option value="'.$rs->fields['state_code'].'"';
                    if  ($rs->fields['state_code'] == $state_code) {echo " selected";}
                    echo  '>'.$rs->fields['state_name'].'</option>';
                    $rs->MoveNext();
                }
                echo '</select>';
            ?>
   </body>
</html>

Java脚本

<script type="text/javascript">
function stateList(val) {
   var select = document.getElementById( "state_list" );
   var url    = "get_statelist.php?country_code="+val;
   $.ajax({
      type: "GET",
      url: url,
      data:'',
      success: function(data){
         $("#state_list").html(data);
      }
   });
}

get_stataelist.php

<?php
session_start();
$country_code = $_GET['country_code'];
$conn        = connect_db()  //Make your own connection entry conn with Server,DB User ID, DB Password and DB Name

if  ($country_code  !=  "") {
    $sql="SELECT * FROM state where coutry_code = '$country_code'  order by state_name";
    $rs=$conn->Execute($sql);

    echo  '<option value="">--Select--</option>';

    $rs->MoveFirst();
    while (!$rs->EOF) {
        echo  '<option value="'.$rs->fields['state_code'].'">'.$rs->fields['state_name']."</option>";
        $rs->MoveNext();
    }
}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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