php - 当我从下拉列表中选择数值时没有获取值?
问题描述:
我想从表中显示的下拉列表中获取值。php - 当我从下拉列表中选择数值时没有获取值?
我尝试过不同的方式,但我不知道我出错的地方。
任何一个可以帮助我在这个..
下面是我的代码。
<tr class="form-field" id="appid">
<div>
<th valign="top" scope="row" >
<label for="country"><?php _e('country', 'custom_table_example')?></label>
</th>
<td>
<select id="country" name="country" class="code" >;
<option value="">select country</option>
<?php
global $wpdb;
$coun_name = $wpdb->get_col("select country_name FROM countries") ;
//print_r($coun_name);
foreach($coun_name as $a)
{
echo '<option value="'. strtolower($a) .'" />' . "$a </option>";
}
?>
</td>
</div>
</tr>
上面的代码显示的值是下拉菜单。
现在的问题是我需要得到选定的值。
echo '<option value="'. strtolower($a) .'"<?php echo $item['country']==".$a."?'selected="selected"':'' ?> />' . "$a </option>";
$ item是我存储所有数据的变量。
country = name属性。
答
您是否设置$item
从$_POST
?你是否使用POST作为你的表单动作?做这样的事情:
<form name='countryTest' method='POST' action='<?/*where your action is going to*/?>'>
<select name='country'>
<?foreach($coun_name as $c){
?><option value='<?echo$c;?>'<?if($_POST['country']==$c)echo' selected="selected"';?><?
}?>
</select>
</form>
或!如果你想成为一个非常酷的人(好吧,不要那么酷但很讨厌)!做一个功能或类功能为你做这一切!
class formHelper{
public function select_form($name,$options=array([0]=>'Please select'),$selected=array(),$multiple=false){//name of select, options, selected options, multiple select
if(!is_array($selected))$selected=array($selected);
$sel='<select name="'.(($multiple===true)?$name.'[]':$name).'"';
if($multiple===true)$sel.=' multiple';
$sel.='>';
foreach($options as $value=>$shown){
$sel.='<option value="'.$value.'" '.((in_array($value,$selected))?'selected="selected"':'').'>'.$shown.'</option>';
}
return$sel.='</select>';
}
}
我们使用它只是这样做
$coun_name=array(merge(array('Please select a country'),$coun_name));
formHelper::select_form('country',$coun_name,$_POST['country']);
编辑
你的错误是你设置你的价值降低,但是当你比较它不降低。见strtolower。你想要做的就是比较低于$item
会更低。我建议你比较像这样在使用整数:
array(
[1]=>'England',
[2]=>'Wales',
[3]=>'Scotland'
);
让你的价值观会
<option value='1'>England</option>
<option value='2'>Wales</option>
<option value='3'>Scotland</option>
但你们您的问题是$item['country']==$a
。需要是$item['country']==strtolower($a)
。并删除与完整的停止字符串引号。 "england"
不等于".England."
。它是“英格兰”的原因已经是因为你已经设置了较低的字符串。除非$item
不是$_POST['county']
'
我编辑过帖子..请看看。 – JMR
我会试试这个.. – JMR
$ item在哪里设置?你是否有一个国家的桌子上的整数? – sourRaspberri