Keep the selected value for dropdown after submit

Discussion in 'PHP' started by SharingEngines, May 31, 2012.

  1. #1
    Hi,

    I have a problem with keep the selected value for dropdown after submit.

    I have this php code and i don´t know how to retain the selected value after submit

    It works ok. But, when script made its work I lose values in boxes, previously selected.

    <form name="search" action="" method="get"><select name="cp_state">
      <?php
      $metakey = 'cp_state';
      $counties = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
      if ($counties) {
        foreach ($counties as $cp_state) {
          echo "<option value=\"" . $cp_state . "\">" . $cp_state . "</option>";
    	  $metakey .= ' selected';
        }
      }
      ?>
    </select>
    <input type="submit" value="search" />
    </form>
    Code (markup):
    Thank you in advance
     
    SharingEngines, May 31, 2012 IP
  2. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #2
    try this

    
    
    <form name="search" action="" method=""><select name="cp_state">
      <?php
      $metakey = 'cp_state';
      $counties = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
      if ($counties) {
        foreach ($counties as $cp_state) {
          echo "<option value=\"" . $cp_state . "\"";
           if ($_POST['cp_state']==$cp_state) {
                echo "selected=\"selected\"";
           }
          echo ">" . $cp_state . "</option>";
    	  $metakey .= ' selected';
        }
      }
      ?>
    </select>
    <input type="submit" value="search" />
    </form>
    
    PHP:
     
    stephan2307, May 31, 2012 IP
  3. SharingEngines

    SharingEngines Member

    Messages:
    83
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #3
    Hi,

    Thank you for your help but he doesen't work.
    He always goes to the first value of drop down.
     
    SharingEngines, May 31, 2012 IP
  4. webmaruchi

    webmaruchi Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You can use selected value in the session and use that value as selected if session variable is exist using isset function
     
    webmaruchi, May 31, 2012 IP