Create A PHP Dropdown Menu From A For Loop?
I am trying to create a drop down menu with the options of 1,2,3 and 4. The below code is what I am using just now and the dropdown is empty. Any idea what I am doing wrong?
Solution 1:
You are not outputting the option tags. Try it like this:
<select name="years">
<?php
for($i=1; $i<=4; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
<option name="years"> </option>
</select>
<input type="submit" name="submitYears" value="Year" />
Solution 2:
You basically use html without closing the php syntax.Your code should look like this:
<select name="years">
<?php
for($i=1; $i<=4; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
<option name="years"> </option>
</select>
<input type="submit" name="submitYears" value="Year" />
Or are you trying to echo the option? In that case you forgot the echo statement:
echo "<option value= ".$i.">".$i."</option>";
Solution 3:
This worked for me. It populates years as integers from the current year down to 1901:
<select Name='ddlSelectYear'>
<option value="">--- Select ---</option>
<?php
for ($x=date("Y"); $x>1900; $x--)
{
echo'<option value="'.$x.'">'.$x.'</option>';
}
?>
</select>
Solution 4:
You forgot something..
Add print
/ echo
before "<option value=".$i.">".$i."</option>";
Solution 5:
place an echo in your loop to output your options.
echo "<option value=".$i.">".$i."</option>";
Post a Comment for "Create A PHP Dropdown Menu From A For Loop?"