user2205507
user2205507

Reputation: 11

How to create a PHP dropdown list

I am trying to build a php contact form with a dropdown list of values, say "A", "B" and "C", that fits the code structure below.

As well, I would like to call this form from a link on another page, and have the value of the dropdown list automatically populated with the passed-in parameter. For example, if the link is "...?val=B", I'd like the dropdown list to automatically set to "B".

I have code below that works for an email field. What does the code look like for a dropdown list?

It's been a long while since I've coded PHP, so any help is appreciated.

<div class="input-field">
<div>
<?php _e('Email','circles'); echo ' <span>('; _e('required','circles'); echo ')</span>'; ?>
</div>
<div class='input-style dlight-grey sc-input'>
<input type="email" name="form_email" size="20" value="<?php echo $form_email; ?>" />
</div>
</div>

Upvotes: 0

Views: 465

Answers (1)

Tianwei Chen
Tianwei Chen

Reputation: 148

Suppose you store options to a html select element(dropdown list) in array $ops

<form>
   <select name='foo'>
      <?php
      $val = $_GET['val'];
      while($option = next($ops)){
         if ($option == $val){
            echo "<option value=$option selected='selected'>$option</option";
         else
            echo "<option value=$option>$option</option>";
      }
      ?>
    </select>
<form>

Alternatively, you can use Javascript to add 'selected' attribute to the option equals to $_GET['val'], see .attr()

Upvotes: 1

Related Questions