我有一个下拉列表,其中填充了我从数据库中获取的值。 我需要根据所选选项执行一些查询,但是首先我需要将所选值保存在新变量中。
这是我的下拉菜单:
<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;它给出了正确的值!
答案 0 :(得分:0)
您的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>