Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.