<form method="post" action="#">
<select name="select">
<?php
foreach($stock as $key => $value):
echo '<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
<option selected="selected" value="<?php echo $search; ?>"><?php echo $search; ?> </option>
</select>
此代码最后为选择框添加了一个新值。但我需要选择一个已存在于选择框中的值。
例如,它包含a,b,c,d
我需要选择c,但是当我使用这个代码时,它变成a,b,c,d,c和最后一个&#34; c&#34;被选中。
有什么想法吗?
答案 0 :(得分:0)
试
<form method="post" action="#">
<select name="select">
<?php
$q = "";
foreach($stock as $key => $value):
if($search = $value ){
$p = '<option selected="selected" value="'.$search.'">'.$search.'</option>';
}
$q = .'<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
echo $p;
echo $q;
答案 1 :(得分:0)
如果值与搜索匹配,请检查循环。所以而不是:
<?php
foreach($stock as $key => $value):
echo '<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
执行:
<?php
foreach($stock as $key => $value)
{
if($search == $value)
echo '<option value="'.$value.'" selected="selected">'.$value.'</option>';
else
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
答案 2 :(得分:0)
它会有所帮助
<select name="select">
<?php
foreach($stock as $key => $value)
{
// This test printing value
$option_selected = "";
if($search == $value){
$option_selected = 'selected="selected"';
}
echo '<option value="'.$value.'" '.$option_selected.'>'.$value.'</option>';
}
?>
</select>
答案 3 :(得分:0)
<html>
<select name="selectu">
<?php
$html = '';
$html1 = '';
$html2 = '';
foreach ($stock as $key => $value):
if ($value == $search):
$html1 = '<option value="' . $value . '" selected="selected">' . $value . '</option>';
else:
$html2 .= '<option value="' . $value . '" >' . $value . '</option>';
endif;
endforeach;
echo $html = $html1 . $html2;
?>
</select>