对于下拉。我想对更新下拉列表应用验证。这一切都很好。更新值插入数据库

For drop down. I want to apply validation for update dropdown. Every this works fine. Updated value inserted in data base

但是当我 select 下拉值和任何与名字等相关的错误时,在更新按钮上它会删除 selected 值并显示旧值。

<td  align=left>Select Month:<select name=month id="month">
<?php 
$date = $row->birth;    
$stamp = strtotime($date); 
?>
<?php
echo '<option .date("m", $stamp). '.$selected.'>'.date("m", $stamp).'</option>';
?>
<option name=""></option>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='12'>December</option>
</select>
<?php echo form_error('month','<div style="color:red">', '</div>'); ?>
<span class="error"></span>
</td>

如果表单验证失败,您可以使用 codeigniter 的 set_select 函数来保留选择:

Select Month:<select name=month id="month">
<option name=""></option>
<option value='01' <?php echo  set_select('month', '01'); ?>>January</option>
<option value='02' <?php echo  set_select('month', '02'); ?>>February</option>
<option value='03' <?php echo  set_select('month', '03'); ?>>March</option>
<option value='12' <?php echo  set_select('month', '12'); ?>>December</option>
</select>

另请参阅:https://www.codeigniter.com/userguide3/helpers/form_helper.html#set_select


如果您想在页面首次加载时在下拉列表中设置一个值,您可以使用第三个参数:

Select Month:<select name=month id="month">
<?php 
$date = $row->birth;    
$stamp = strtotime($date); 
$month = date("m", $stamp);
?>
<option name=""></option>
<option value='01' <?php echo  set_select('month', '01', $month == '01'); ?>>January</option>
<option value='02' <?php echo  set_select('month', '02', $month == '02'); ?>>February</option>
<option value='03' <?php echo  set_select('month', '03', $month == '03'); ?>>March</option>
<option value='12' <?php echo  set_select('month', '12', $month == '12'); ?>>December</option>
</select>