[英]Show selected value in dropdown after submit button
我正在嘗試在提交按鈕后的下拉列表中打印選定的值。 這是我的PHP函數。
if( !function_exists('mad_get_towns_list') ):
function mad_get_towns_list(){
$towns_list='';
if(mad_get_towns()){
foreach(mad_get_towns() as $town){
$towns_list .= '<option value="'.$town.'">'.$town.'</option>';
}
return $towns_list;
}
return false;
}
endif;
這是我得到的所有列表。問題是,當我提交按鈕時,它顯示的是Any,它沒有顯示選定的值。
<select name="city_location" class="custom-select full-width" id="s_country" data-live-search="true" value="<?php echo $_POST['city_location'];?>">
<option value="">Any</option>
<?php
print_r(mad_get_towns_list());
?>
</select>
您必須為<select>
標簽使用selected
屬性而不是value。 因此,您可以將當前值傳遞到函數中以添加此屬性:
if (!function_exists('mad_get_towns_list')) :
function mad_get_towns_list($selected_value) { // pass value, see below
$towns_list='';
$towns = mad_get_towns(); // store variable
if (!empty($towns)) {
foreach($towns as $town) {
$selected = $selected_value == $town ? " selected" : "" ; // create select attribute
$towns_list .= '<option value="'.$town.'" '.$selected.'>'.$town.'</option>';
}
}
return $towns_list;
}
endif;
?>
<select name="city_location" class="custom-select full-width" id="s_country" data-live-search="true">
<option value="">Any</option>
<?php
$selected = isset($_POST['city_location']) ? $_POST['city_location'] : '' ;
echo mad_get_towns_list($selected) ;
?>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.