How to populate Listbox / dropdown box /select box

2019-08-30 09:13发布

问题:

I need write a custom array or JSON to populate a Listbox/dropdown box/select box and add an attribute selected="selected".

For example:

<select id="test1" name="selectB" class="Field">
<option value="NO" selected="selected">No (Recommended)</option>
<option value="YES">Yes</option>
</select>

I cannot figure out how to do this.

回答1:

<?php
$array = array(
    array("value"=>"NO","label"=>"No (Recommended)","selected"=>true),
    array("value"=>"YES","label"=>"Yes","selected"=>false),
);


?>

<select>
    <?php foreach($array as $option) { ?>
        <option value="<?php echo $option['value'] ?>" <?php if($option['selected']){ ?>selected="selected"<?php }?>>
             <?php echo $option['label'] ?>
        </option>
    <?php }?>
</select>

json equivalent of the array is:

[{"value":"1","label":"No (Recommended)","selected":true},{"value":"2","label":"Yes","selected":false}]

which is the output of json_enconde($array);