set_select for select tag in codeigniter

2019-01-28 22:07发布

问题:

How to set value for select tag ,as when i tried for text field

<input type="input" name="name" value="<?php echo set_value('name') ?>"/>

its working but when i tried for select tag

<SELECT class="form-control" name="user" style="width:200px;">
    <option value="">--Select--</option>
    <?php
        foreach ($result as $row):
        echo "<option value='" . $row['id'] . "' >" . $row['employee_name'];
    ?>
    <?php endforeach ?>
</SELECT>

its not working ,when validation run falls its again showing --Select-- option

回答1:

try this--> use set_select()

<select id="user" name="user" style="width: 230px; height: 40px;" >
<option value="" selected>--Select--</option>
<?php foreach ($result as $row) { ?>
<option value="<?php echo $row['id'] ; ?>" <?php echo set_select('user', $row['id'], False); ?> ><?php echo $row['employee_name'] ; ?> </option> 
<?php } ?>
</select>


回答2:

best way is to use form_dropdown method to use these as you are already looping and creating options create option array in controller and pass it to view like

$options = array('--Select--');

foreach ($result as $row){
     $options[$row['id']] = $row['employee_name'];
}

echo form_dropdown('user',$options,set_select('user','default_value'));

if not any select value from dropdown then default value will be used



回答3:

For Codeigniter Dropdown list you should use set_select() instead of set_value() function. You can use like

<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> 


回答4:

this might help you.

<SELECT class="form-control" name="user" style="width:200px;">
    <option value="">--Select--</option>
    <?php
        foreach ($result as $row):
        echo "<option value='".$row['id']."' set_select('user', $row['id']);.">". $row['employee_name'];
    ?>
    <?php endforeach ?>
</SELECT>