簡體   English   中英

獲取選定的下拉列表值-PHP

[英]Get selected Dropdown value - PHP

我有一個下拉列表,其中填充了從數據庫中獲取的值。 我需要基於所選選項執行一些查詢,但是首先我需要將所選值保存在新變量中。

這是我的下拉菜單:

<form name="dashboard_form" action="" id="dashboard_form" method="post">
    <tr>
     <td><?php _e('Select City')?>:</td>
     <td>
        <select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
        <?php
          foreach ( $all_cities as $city ) 
           {
            echo '<option value='.$city->ID.'>'.$city->name.'</option>';
           }
         ?>
        </select>
        </td>
     </tr>
</form>

* $ all_cities是一個包含所有城市的數組。

我的jQuery:

<script>
            jQuery("#dashboard_form").validate({
                ignore:'',
                rules: {
                    'selected_city': {
                     required: true
                }},
                messages: {
                    'selected_city': "Please Select a City",
                },
                errorPlacement: function(error, element) {
                    jQuery(element).closest('tr').next().find('.error_label').html(error);
                }
            });
</script>

如何從下拉列表中將我選擇的值保存在$ new_variable上?

編輯1:

我添加了以下內容

$(document).ready(function () {
    var selected_city;

    $('.selected_city').change(function() {
        selected_city = $(this).val();
        alert(selected_city);
    });
});

警報(selected_city)打印正確的城市,如何在PHP上使用這個selected_city?

EDIT2:問題是下拉列表未提交任何內容,因此我創建了一個Button來強制其提交:

 <input type="submit" value="<?php _e('Send Now')?>" name="send_now_button" id="send_now_button" class="button button-primary">

然后:

if(isset($_POST['send_now_button'])){
        if(isset($_POST['selected_city'])) { $selected_city = $_POST['selected_city']; } else {$selected_city = 'Lisboa';  } }

現在當我回顯$ selected_cities_id; 它給出正確的值!

您的HTML無效。 <tr>不能是<form>的子代,它必須是<table><tbody><thead><tfoot>的子代。 這可能會阻止<select>被視為表單的一部分,因此未提交任何內容。

您需要將表格放在整個表格周圍。

<form name="dashboard_form" action="" id="dashboard_form" method="post">
    <table>
        ...
        <tr>
            <td><?php _e('Select City')?>:</td>
            <td>
                <select class="selected_city" name="selected_city" style="margin: 20px;width:300px;" required>
                <?php
                foreach ( $all_cities as $city ) 
                {
                    echo '<option value='.$city->ID.'>'.$city->name.'</option>';
                }
                ?>
                </select>
            </td>
        </tr>
        ...
    </table>
</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM