cnbigfoot 发表于 2009-11-2 18:24:58

在select中设定初始值

我有一张表单,其中有一个select菜单,我选中其中的一项后提交,因为该表单没有验证合格,又返回到表单页面。
我在表单中了set_select,但是返回的表单页面始终都不是我提交时选中的那一项,这是什么原因呢?

Hex 发表于 2009-11-2 18:45:49

看一下 HTML 代码

cnbigfoot 发表于 2009-11-2 20:21:27

form控制器:
<?php

class Form extends Controller {

function index()
{
$this->load->helper(array('form', 'url'));

$this->load->library('form_validation');
   
$this->form_validation->set_rules('username', 'Username', 'required');

   
if ($this->form_validation->run() == FALSE)
{
   $this->load->view('myform');
}
else
{
   $this->load->view('formsuccess');
}
}
}
?>

myform的view:
<html>
<head>
<title>My Form</title>
</head>
<body>

<?php echo validation_errors(); ?>

<?php echo form_open('form'); ?>

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<br />

<select name="myselect">
        <option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
        <option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
        <option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
</select>

<div><input type="submit" value="Submit" /></div>

</form>

</body>
</html>


formsucuess的view:
<html>
<head>
<title>My Form</title>
</head>
<body>

<h3>Your form was successfully submitted!</h3>

<p><?php echo anchor('form', 'Try it again!'); ?></p>

</body>
</html>


现在的问题是:如果我在下拉菜单中选择第二项,当username没有验证通过,再次回到form页面时,下拉菜单中默认选择的还是第一项,而不是我选择的第二项。

其实这就是用户手册中 表单验证类 中的例子。使用:
<input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox('mycheck[]', '1'); ?> />
<input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> />

<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
也是一样的,如果验证不能通过再次回到表单页面时,先前选择的数据都不能显示。
页: [1]
查看完整版本: 在select中设定初始值