Jump to content

keep dropdown value selected whatever it maybe ?


Go to solution Solved by Muddy_Funster,

Recommended Posts

ok i made this dropdown which auto populate, but supposing if i store some value in db how on earth i fetch that value  matching with my following code?

 

if db value is like year 1999 how do i get it to show in my current dropdown?

 

<select name="reduyear5" required>
                <option value="" selected="selected" disabled="disabled">Select Passed Year</option>
                <option value="Persuing">Persuing</option>
                <?php
                    $start_year = date('Y')-45;
                    $end_year   = $start_year+45;
                    for($i=$start_year; $i<=$end_year; $i++){
                    echo '<option>'.$i.'</option>';
                    }
                   ?>                   
                </select>

  • Solution

You just put a conditional check into the loop as it's constructing the option list (assuming you have already dealt with getting the desired value such as 1999) and set the selected attribute when the loop matches the conditional.

for($i=$start_year; $i<=$end_year; $i++){
if ($i == $valueFromDB){
echo "<option value='{$i}' selected='selected'>{$i}</option>";
}
else{
echo "<option value='{$i}'>{$i}</option>";
}
}

you could even use a ternary operator to condense the if/else:

($i == $valueFromDB) ? echo "<option value='{$i}' selected='selected'>{$i}</option>" : echo "<option value='{$i}'>{$i}</option>";
  • Like 1
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.