繁体   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