开发者

How repopulate/reselect/autoselect the multiple select box values on basis of csv from database?

I have a form which is displayed when there is some editing is required in data. This form contains the multiple s开发者_StackOverflow社区elect box field i.e.,

<select name="multiple" multiple>
        <option value="1">asd</option>
        <option value="2">asaad</option>
        <option value="3">aslan</option>
</select>

Now when i come to this form, I get every existing values populated in their respective fields but i do not get this multiple select box populated. In db the its respective values are stored in csv format like, 2,3,4.

Now how Can i use these csv and repopulate the multiple select box respective of the csv.?


<?
$csvString = "1,3";

?>
<select name="multiple" multiple>
    <option value="1" <?=strpos($csvString ,'1')!== false?'selected="selected"':''?> >Option 1</option>
    <option value="2" <?=strpos($csvString ,'2')!== false?'selected="selected"':''?> >Option 2</option>
    <option value="3" <?=strpos($csvString ,'3')!== false?'selected="selected"':''?> >Option 3</option>
</select>


I assume you generate HTML for selectbox iterating over the $options. Then you just have to check in each iteration if the current value is present in you $csv and add the selected parameter to the option.

$selection = explode(',', $csv);
foreach ($options as $value => $name) {
    $selected = in_array($value, $selection) ? ' selected="selected"' : '';
    echo '<option value="'. $value .'"'. $selected .'>'. $name .'</option>';
}


This may help but there is probably a better way...

$csvString = "1,3";
$options = explode(",", $csvString);
foreach($options as $val) {
    ${"opt".$val} = "selected=\"selected\"";
}
?>
<select ...>
    <option value="1" <?php echo $opt1 ?> >Option 1</option>
    <option value="2" <?php echo $opt2 ?> >Option 2</option>
    <option value="3" <?php echo $opt3 ?> >Option 3</option>
</select>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜