Jump to content

[SOLVED] form select help


sasori

Recommended Posts

i have this select form for a year option

echo "<select name='Year'>\n";
$year = date('Y');
for($i=$year; $i<=$year+7; $i++)
{
echo "<option value='$year' ";
if($i == date('Y',time()))
{
	echo " selected ";
}
echo "> $i </option>\n";
}
echo "</select>\n";

the code is working fine at first glance of the page..but when i refresh the page, the selected

years turns to the last value :(

let's say today is 2008 but when i click refresh button of the browser

it turns to 2015 :(

what should i do now so that even if i refresh the page it will still select the current year such as

2008 ? ???

Link to comment
https://forums.phpfreaks.com/topic/123261-solved-form-select-help/
Share on other sites

Looks like you have the gist of it, but you have a couple references out of place in your code. For instance, your value is always set to $year, so no matter what is selected, you will always have this year's value submitted. Here is how I would do it, but it really is only slightly different from what you have:

<?php
echo "<select name=\"year\">\n";
$y = date('Y');
for ($i = $y; $i < ($y + 7); $i++)
{
  echo "<option value=\"$i\"";
  echo $y == $i ? ' selected="selected"' : '';
  echo ">$i</option>\n";
}
echo "</select>\n";
?>

 

Since you are initially priming $i to the current year, you shouldn't have to check at all, really. A select field always defaults to its first value, so unless you are wanting to compare against other options, you may not have to do the comparison at all.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.