3

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?

<select name="years">
<?php 

for($i=1; $i<=4; $i++)
{

"<option value=".$i.">".$i."</option>";
}
?> 
     <option name="years"> </option>   
        </select> 

            <input type="submit" name="submitYears" value="Year" />

7 Answers 7

9

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" />
Sign up to request clarification or add additional context in comments.

Comments

1

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>"; 

Comments

1

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>

Comments

0

You forgot something..

Add print / echo before "<option value=".$i.">".$i."</option>";

1 Comment

Thank you! It's always the little things that get forgotten about!
0

place an echo in your loop to output your options.

echo "<option value=".$i.">".$i."</option>";

Comments

0

Just echo the <option> tag

echo "<option value=".$i.">".$i."</option>";

Comments

0
<select name="year">
    <?php for ($i = 0; $i <= 9; $i++) : ?>
         <option value='<?= $i; ?>' <?= $fetchData->year == $i ? 'selected' : '' ?>><?= $i; ?></option>
    <?php endfor; ?>
</select>

2 Comments

<?= $fetchData->year == $i ? 'selected' : ' ' ?> using when you saved and edit from same page this code will show your selected option by fetched data from database.
Please edit your answer to contain all explanaation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.