views:

338

answers:

2
<form method="get" action="">
   <select name="name">
      <option value="a">a</option>
      <option value="b">b</option>
   </select>
   <select name="location">
      <option value="x">x</option>
      <option value="y">y</option>
   </select>
   <input type="submit" value="Submit" class="submit" />
</form>

On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside wordpress (PHP).

Thanks

+3  A: 
<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
Ignacio Vazquez-Abrams
Is it the best method? There're too many options in my form.
Nimbuz
If the `option` tags are being generated in code (and if they aren't, then why not?) you can just put the check within the loop.
Ignacio Vazquez-Abrams
+2  A: 

To avoid many if-else structures, let javascript do the trick automatically:

 <select name="name" id="name">
  <option value="a">a</option>
  <option value="b">b</option>
 </select>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>

 <select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>
 </select>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
Sarfraz
Perfect! Thanks heaps! :)
Nimbuz
@Nimbuz: you are welcome and thanks :)
Sarfraz