我有这行代码允许用户输入状态;
<input id="location-state" type="text" maxlength="2" name="location_state" value="<?php echo esc_attr($EM_Location->location_state, ENT_QUOTES); ?>" />
但是,我想将其更改为下拉选项。现在我想做的一种方法是使用php并获取选择选项值并将其添加到上面的输入,然后隐藏用户看到它的输入。
不知道从哪里开始,我已经尝试过以下作为测试,但没有工作;
<select>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AL'); ?>">Alabama</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AK'); ?>">Alaska</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AZ'); ?>AZ">Arizona</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AR'); ?>AR">Arkansas</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'CA'); ?>CA">California</option>
</select>
它确实有点工作,但仅适用于阿拉巴马州......
答案 0 :(得分:1)
$values = array(
'AL' => 'Alabama',
'AK' => 'Alaska',
'AZ' => 'Arizona'
...
);
echo '<select id="location-state" name="location_state">';
foreach( $values as $key => $value )
{
$selected = $key == $EM_Location->location_state ? 'selected="selected"' : '';
echo '<option value="'.$key.'" '.$selected.'>'.$value.'</option>';
}
echo '</select>';
答案 1 :(得分:0)
您需要删除输入标记,并为select标记赋予一个与输入值相同的属性名称。 删除它:
<input id="location-state" type="text" maxlength="2" name="location_state" value="<?php echo esc_attr($EM_Location->location_state, ENT_QUOTES); ?>" />
并添加:
<select name="location_state">
<option value="<?php echo esc_attr($EM_Location->location_state, 'AL'); ?>">Alabama</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AK'); ?>">Alaska</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AZ'); ?>AZ">Arizona</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'AR'); ?>AR">Arkansas</option>
<option value="<?php echo esc_attr($EM_Location->location_state, 'CA'); ?>CA">California</option>
</select>
您无需更改您的PHP代码。