Select index's and HTML Forms

Discussion in 'JavaScript' started by dai.hop, Oct 9, 2006.

  1. #1
    Hi All,

    I'm looking for a function that will allow me to achieve the following:

    A user chooses an option from a drop down selection list and submits the form using $_SERVER['PHP_SELF']. When the form is reloaded, the option that was chosen is still selected in the list.

    Any help / hints / example code would be greatly appreciated!

    :)

    Many Thanks,

    dai.hop
     
    dai.hop, Oct 9, 2006 IP
  2. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #2
    That doesn't require Javascript at all. Simply determine which option was posted and mark it as selected in the markup you send back.

    If you had this select/option element group:
    <select name="fruit_type">
      <option value="apple">Apple</option>
      <option value="pear">Pear</option>
      <option value="orange">Orange</option>
    </select>
    HTML:
    You could use this simple bit of logic in your PHP script to determine the option to select:
    <select name="fruit_type">
      <option value="apple"<?php echo $_POST['fruit_type'] === 'apple' ? ' selected="selected"' : '' ?>>Apple</option>
      <option value="pear"<?php echo $_POST['fruit_type'] === 'pear' ? ' selected="selected"' : '' ?>>Pear</option>
      <option value="orange"<?php echo $_POST['fruit_type'] === 'orange' ? ' selected="selected"' : '' ?>>Orange</option>
    </select>
    
    PHP:
    Gets a bit messy and redundant though - you could try this as an improvement:
    <?php
      $fruit_options = array(
        'apple' => 'Apple',
        'pear' => 'Pear',
        'orange' => 'Orange'
      );
    
      foreach($fruit_options as $key_name => $friendly_name):
    ?>  <option value="<?php echo $key_name ?>"<?php echo $_POST['fruit_type'] === $key_name ? ' selected="selected"' : '' ?>><?php echo $friendly_name ?></option>
    <?php
      endforeach;
    ?>
    
    PHP:
    Hope that gives you some ideas. :)
     
    penagate, Oct 9, 2006 IP