Jump to content

creating function so that selected data in drop down menus are displayed


runnerjp

Recommended Posts

hey guys im wondering ... is it possible for sum kind of function that makes it so that the data already selected is displayed in all drop down menus ect ??

because atm i have to do this

 

<select class="input" id="gender" name="gender"> 
<option value="Male" <?php if($gender == 'Male') echo 'selected'; ?>>Male</option>
<option value="Female"  <?php if($gender == 'Female') echo 'selected'; ?>>Female</option>
</select>

for everything

Link to comment
Share on other sites

Just about every time I create froms with PHP, I have the PHP script generate the froms based on data from an array or database. Here is a sample that might work for you:

 

<?php
function print_options($values, $selected_value)
{
  $output = '';
  foreach($values as $value)
  {
    $output .= "<option value='{$value}' ";
    if ($value == $selected_values))
    {
      $output .= " selected='selected' ";
    }
    $output .= ">{$value}</option>\n";
  }
  return $output;
}
echo '<select class="input" id="gender" name="gender"> ';
echo print_options(array('Male', 'Female'), 'Male')
echo </select>;
?>

 

 

Using PHP as a HTML 'template' system can be a real pain. For something like this, use PHP as a scripting language that dynamically generates the data.

 

Remember: If you find youself writing out big lists or redundant code, then you are doing something wrong. Programming should be fun. There is no need to type the same thing over and over again.

Link to comment
Share on other sites

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.