0

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.

2
  • Can you elaborate? Where is your data coming from? You want php to take the results of a database query, and create a select with that? Commented Mar 9, 2011 at 17:47
  • This very similar question was just posted: stackoverflow.com/questions/5249825/… Commented Mar 9, 2011 at 17:48

1 Answer 1

2
<?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);

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I like how you adapted your answer on stackoverflow.com/questions/5249825/…. :)
Can you ,please, tell me how to use JSON mode - function to output the results ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.