Jump to content

Select a default value from a drop down list(select) using GET


cjjubb

Recommended Posts

Hi all.

 

I am have created the following drop down list using standard HTML tags.

 

<select >

  <option value ="volvo">Volvo</option>

  <option value ="saab">Saab</option>

  <option value ="opel" >Opel</option>

  <option value ="audi">Audi</option>

</select>

 

This drop down list is part of an HTML form that is then submitted using the 'GET' method.  The user is then returned to the form following the submission.

 

When the user is returned to this form I would like the value they selected from the drop down prior to submission to be selected (i.e. if they selected 'Opel' I would like 'Opel' to be selected by default).

 

Any help would be grately appreciated.

 

Many Thanks

I had done a similar thing in asp, hopefully you can use this code to adapt to php if you want, it should be close

<select name="Product">
<%
Dim prodArray,prod
prodArray = Array("Prod1","Prod2","Prod3","Prod4","Prod5")
for each prod in prodarray
	Response.Write("<OPTION")
	if(strComp(prod,rs("Product"),1)=0) then
		Response.Write(" selected=""selected"">")
	else
		Response.Write(">")
	end if
	Response.Write(prod)
next
%>
</select>

 

basically, take all of the options the user has and insert them into an array.  using a foreach loop, go through each element in the array and check to see if it matches what the user had selected previously.  If it does, put <selected="selected"> in the OPTION tag.  if not, just use the OPTION tag by itself

Here it is:

 

<?php
$favcar = array("volvo", "saab", "opel", "audi");
?>
<select name="favcar">
  <option value=""> </option>
  <?php
    foreach($favcar as $name) {
      if ($name == $_GET['favcar']) {
        print "<option value=\"$name\" selected>$name</option>";
      } else {
        print "<option value=\"$name\">$name</option>";
      }
    }
  ?>
</select>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.