selected item ind dropdown when editing

2019-03-02 04:29发布

问题:

i have this code right here:

<select name="group">
    <option value="">Choose a group....</option>
    <?php foreach($groups as $group):?>
        <option value="<?php echo $group['groupID']?>" selected="yes"><?php      echo     $group['name']?></option>

    <?php endforeach;?>
</select>

my question is how would i code the 'option' tag in my dropdown so that when i edit an existing data, the selected group(admin, users, moderators) of the data i will be editing will appear when i edit it.thanks.

回答1:

The selected="yes" HTML attribute of the option tag should be only one. You need to put it on the right group.

Set a PHP variable like $selected_group that is true if the group is the right one, and print the selected attribute only for that group. Set it to false instead.

For example, if your selected group id is putted as a request parameter called groupID you should use the code below:

<select name="group">
    <option value="">Choose a group....</option>
    <?php foreach($groups as $group):?>
    <?php if ($group['groupID'] == $_REQUEST['groupID']) $selected_group = true; else $selected_group = false; ?>
        <option value="<?php echo $group['groupID']?>" <? if ($selected_group) echo 'selected="yes"'; ?>><?php      echo     $group['name']?></option>

    <?php endforeach;?>
</select>

You could set the chosen groupid as a array member inside $groups, for example:

$groups[0]['selected'] = true;

In this case change the line inside the loop like this one:

<?php if ($group['selected']) $selected_group = true; else $selected_group = false; ?>