I have a dropdown populated with values I get from the database. I need to perform some queries based on the selected option, but first I need to save the selected value on a new variable.
This is my dropdown:
<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 is an array with all the cities.
My 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>
How can I save on a $new_variable my selected value from the dropdown?
EDIT 1:
I added the following to
$(document).ready(function () {
var selected_city;
$('.selected_city').change(function() {
selected_city = $(this).val();
alert(selected_city);
});
});
The alert(selected_city) prints the correct city, how can I use this selected_city on the PHP?
EDIT2: The problem is the dropdown is not submitting anything, so I created a Button to force it to Submit:
<input type="submit" value="<?php _e('Send Now')?>" name="send_now_button" id="send_now_button" class="button button-primary">
Then:
if(isset($_POST['send_now_button'])){
if(isset($_POST['selected_city'])) { $selected_city = $_POST['selected_city']; } else {$selected_city = 'Lisboa'; } }
Now when I echo $selected_cities_id; it gives the correct value!