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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.