ninpot18 ninpot18 - 2 months ago 8
PHP Question

get selected month value in dropdown list if using an array

I am trying to get the selected value in the drop down; but the items inside it are in an array. How can I get the value of the selected option?

For now, I have these lines of code:

<?php
// lowest year wanted
$cutoff = 2013;

// current year
$now = date('Y');

// build months menu
echo '<select name="month">' . PHP_EOL;
for ($m=1; $m<=12; $m++) {
echo ' <option value="' . $m . '">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

// build days menu
echo '<select name="day">' . PHP_EOL;
for ($d=1; $d<=31; $d++) {
echo ' <option value="' . $d . '">' . $d . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

// build years menu
echo '<select name="year">' . PHP_EOL;
for ($y=$now; $y>=$cutoff; $y--) {
echo ' <option value="' . $y . '">' . $y . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;
?>


Let's say, I picked July for the month. How can I tell the browser that I have chosen July. Any idea?

Answer

Try like this

echo '<select name="month">' . PHP_EOL;
for ($m=1; $m<=12; $m++) {
    if($sel_mnth == $m)
        echo '  <option value="' . $m . '" selected="selected">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
    else   
        echo '  <option value="' . $m . '">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}
echo '</select>' . PHP_EOL;

or directly

for ($m=1; $m<=12; $m++) {                   
        echo '  <option value="' . $m . '" if($sel_mnth == $m) echo "selected=\'selected\'";>' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
}
Comments