Theun Arbeider Theun Arbeider - 4 months ago 12
HTML Question

Set Selected value after php foreach

Currently I fill a select box with the following code:

<select name="klas_jaar" value="{jaar_id}">
<?php foreach ($jaren as $jaar):?>
<option value="<?=$jaar->jaar_id?>"><?=$jaar->schooljaar?></option>
<?php endforeach;?>
</select>


The value set is the same id as a option's value.. however it doesn't put the requested value as selected when going to this page.

What am I doing wrong?

Answer

select tags don't have a value attribute. Instead, you have to drop a selected attribute in the appropriate option.

<select name="klas_jaar">
    <?php foreach ($jaren as $jaar):?>
        <option value="<?=$jaar->jaar_id?>"<? if($jaar->jaar_id == $selected_jaar_id) echo " selected"?>><?=$jaar->schooljaar?></option>
    <?php endforeach;?>
</select>
Comments