Ben Kulbertis
Ben Kulbertis

Reputation: 1713

Automatically select option from select menu with link

I am trying to use php (and if not php, javascript) to link to a page and include a "?type=foo" or "#foo" at the end of the link so that when the linked page loads it will automatically select a specific option, depending on the end of the link, from a dropdown menu in a form. I have tried to search for this but do not know what this action is actually called, but I've seen it done before. Does anyone know how to achieve this? Thanks very much.

Upvotes: 1

Views: 2436

Answers (2)

mqchen
mqchen

Reputation: 4193

If the option is in a <select> then the name you are looking for is the selected attribute. It can be applied to each <option> tag, like so: W3Schools.

Using that you can simply use a PHP if-statement, eg:

<?php

$options = array('Norway', 'United States', 'Springfield');

echo '<select>';

foreach($options as $country) {
    if(array_key_exists('selected', $_GET) && $_GET['selected'] === $country) {
        echo '<option selected="selected">'.$country.'</option>';
    }
    else {
        echo '<option>'.$country.'</option>';
    }
}

echo '</select>';

If the query is ?country=Norway then Norway would be selected when the page loads.

It can of course be solved using javascript as well.

Upvotes: 0

Luke Stevenson
Luke Stevenson

Reputation: 10341

When I have created these in the past, for ease of use, I have simply inserted the selected value in the top of the select object, rather than roll through the whole list and mark the selected one as such when it is encountered.

Assuming the page is called like page.php?theSelectedList=Cougar:

<select name="theSelectList">
  <?php
    if( isset( $_GET['theSelectList'] ) )
      echo '<option selected="selected">'.$_GET['theSelectList'].'</option>';
  ?>
  <option>Aardvark</option>
  <option>Baboon</option>
  <option>Cougar</option>
  <option>Dog</option>
  <option>Elephant</option>
</select>

In that case, the option for Cougar would be displayed twice - once at the top of the list, and selected, and again further down the list in the normal location. This may sound confusing, but, in the instances I have used it, it has been quite intuitive.

It's nice and simple, but, I will mention the caveat, that the above would need a bit of re-jigging if the Option Labels and the Option Values are different (like it each option has a numeric value, but a text label.

Upvotes: 1

Related Questions