bonaca bonaca - 1 year ago 34
PHP Question

write selected attribute on dinamically written options

two

select
tags -
months
and
years
:

<select class='sx' id ='sxa'>
<?php
$months = array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC');
for($x = 0; $x < count($months); $x++) {
$i = sprintf('%02d', $x+1);
echo "<option value=" . $i . ">" . $months[$x] . "</option>\n";
}
?>
</select>

<select class='sx' id ='sxb'>
<?php
$current = date('Y');
for ($x = 2016; $x <= $current; $x++) {echo "<option>$x</option>";}
?>
</select>


Is there a way to insert attribute
selected
on current month and year ?

In case of years this is always the last option, while in months it could be on any index.

Answer Source

You can check if the current month is equal to the loop index + 1.

$currentMonth = date('n');

Then in your loop:

<?php for($x=0; $x<count($months); $x++): ?>
    <?php $i = sprintf('%02d', $x + 1); ?>
    <option value="<?php echo $i; ?>"<?php if($x + 1 == $currentMonth) echo ' selected'; ?>>
        <?php echo $months[$x]; ?>
    </option>
<?php endfor; ?>

Or if you want to echo it your way:

<?php
    for($x=0; $x<count($months); $x++){
        $i = sprintf('%02d', $x + 1);
        echo '<option value="' . $i . '"' . ($x + 1 == $currentMonth ? ' selected' : '') . '>' . $months[$x] . '</option>';
    }
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download