Jon
Jon

Reputation: 976

What is the best way to figure out which drop down menu item should be active?

I have a page where the user can edit their information. One of the ways for the user to input information is a drop down menu. I have the value already and I need to make that value the active selection on the drop down menu. I know the most straightfoward way of doing with a bunch of if statements:

if ($classVal == "Freshman") {
  echo "
  <select name='class'>
    <option selected>Freshman</option>
    <option>Sophomore</option>
    <option>Junior</option>
    <option>Senior</option>
  </select>
  ";
  } else if ($classVal == "Sophomore") {
    echo "
    <select name='class'>
    <option>Freshman</option>
    <option selected>Sophomore</option>
    <option>Junior</option>
    <option>Senior</option>
    </select> </p>
    ";
    } else if ($classVal == "Junior") { ... }

This way has worked for me but I was wondering if there was a better way of accomplishing this.

Upvotes: 1

Views: 61

Answers (2)

Steve
Steve

Reputation: 20469

    <?php
    $options = array('Freshman','Sophomore','Junior','Senior');
    ?>

    <select name='class'>
    <?php foreach($options as $op):?>
        <option<?php echo $classVal==$op?'selected':'';?>> <?php echo $op;?> </option>
    <?php endforeach;?>
    </select>

Upvotes: 1

Goran.it
Goran.it

Reputation: 6299

You can test var inline like this :

 echo "
  <select name='class'>
    <option ".($classVal == "Freshman" ? "selected" : "").">Freshman</option>
    <option ".($classVal == "Sophomore" ? "selected" : "").">Sophomore</option>
    <option ".($classVal == "Junior" ? "selected" : "").">Junior</option>
    <option ".($classVal == "Senior" ? "selected" : "").">Senior</option>
  </select>
  ";

Upvotes: 5

Related Questions