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

时间:2014-03-30 22:37:47

标签: javascript php jquery html mysql

我有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”的值,其中第一个选择例如。 “食物”等于数据库中的“食物”。

因此,如果我在第一个下拉框中选择“食物”,则第二个下拉框将仅显示“Curries”& “肉”。

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>

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

2 个答案:

答案 0 :(得分:1)

您可以使用请求创建一个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>

答案 1 :(得分:0)

我有一个简单的解决方案,可以根据国家/地区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();
    }
}

?>