问题
I chose to use tag instead of form_dropdown()
from Form Helper because i can't set a class atribute to <option>
tag.
So I have a <select>
and want to set a item with as "selected"
. This data is coming from database. How I set this?
I saw this: set_select()
but I can't make work.
Does anyone have a solution?
回答1:
From the docs on the form_dropdown function:
form_dropdown()
Lets you create a standard drop-down field. The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected.
echo form_dropdown('shirts', $options, 'large'); // 'large' will be "selected"
回答2:
There are two things to keep in mind: First you have to use the validation class to be able to use the set_select()
function. Second you have to pass the database information to that function, like this:
<select name="myselect">
<option value="one" <?php echo set_select('myselect', 'one', ($model->selection == 'one')); ?> >One</option>
<option value="two" <?php echo set_select('myselect', 'two', ($model->selection == 'two')); ?> >Two</option>
<option value="three" <?php echo set_select('myselect', 'three', ($model->selection == 'three')); ?> >Three</option>
</select>
If $model->selection
is two
, then the second option will be selected in the example above.
回答3:
<?php echo form_label('Gender:'); ?>
<?php echo form_dropdown(array('id'=>'selectinform', 'name'=>'gender', 'options'=>array('1'=>'Select', '2'=>'2','3'=>'3'), 'selected'=>'1')); ?>
'selected'=>'1'
来源:https://stackoverflow.com/questions/9012217/set-a-selected-option-in-menu-dropdown-with-codeigniter