Skip to content Skip to sidebar Skip to footer

An Option Already Selected On Page Load In Drop Down List And Also Changeble

Possible Duplicate: PHP - PRE-select drop down option I have a situation in my php project where a user can edit his account. In editing, there is a city field which is a dro

Solution 1:

<divclass="search_bar1_txt">State:</div><divclass="search_bar1"><selectclass="styled"name="state_trainer"><option<?if($value['city']=='-select-') echo"selected";?>>-select-</option><option<?if($value['city']=='washington') echo"selected";?>>washington</option><option<?if($value['city']=='perth') echo"selected";?>>perth</option><option<?if($value['city']=='delhi') echo"selected";?>>delhi</option><option<?if($value['city']=='london') echo"selected";?>>london</option></select></div></div>

Solution 2:

You can do it in a number of ways, the simplest (and probably least elegant) is to do something like this:

<selectclass="styled"name="state_trainer"><?php$myCity='london'; // assumed to be data from database...echo'<option'.($myCity=='-select-') ? ' selected ' : ' ' .'-select-</option>';
echo'<option'.($myCity=='washington') ? ' selected ' : ' ' .'washington</option>';
?>

This is of course horrid.

I would rather suggest that you check the data as you are pulling your information out of the database and putting your initial dropdown list together.

If you are making an array of data to create the drop down list (for example) check it right there and then. If the city matches what you want, do it inside your loop right off the bat.

$usersCity="london";
$myCityList=array();

while( ... ) // Database loop that is pulling the data from the database.
{
    $selected='';
    if($userCity==$row['city'])
    {
        $selected=' selected ';
    }
    $myCityList[]='<option'.$selected.'>'.$row['city'].'</option>';
}

Then to display the drop down list, you can simply do this:

$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
    echo$myCityList[$i].'\n';
}

The users city will already be selected.

Solution 3:

I'm not sure if it is clear way but you can put code inside every option cell like this:

<option<?phpif($value['city'] == "washington") echo"selected=selected"; ?> >washington</option>

Solution 4:

This way you can get what u want. And better use mysqli function for database interactions.

<option<?phpif ($value['city'] == delhi)
          {
                                echo"selected = true"; 

          }  ?> 
 >delhi
</option>

Solution 5:

Just het the selected value form db like

$choosen = $some value form db

then $options = array(1 => 'data1', 2 => 'data2', 3 => 'data3'); foreach ($options as $key => $value) { echo '' . $value . ''; }

to get your selection box in php.I thnk you understand,it works for me

Post a Comment for "An Option Already Selected On Page Load In Drop Down List And Also Changeble"