Jump to content

define which option is selected depending on form input


RLJ

Recommended Posts

Hi, I have an html form in "send.htm" that sends data to "retrieve.php" with the following structure:

 

send.htm:

<html>
<body>

<form method="post" action="retrieve.php"
<select id='select' name='select' >
                        <option>option1</option>
                        <option>option2</option>
                        <option>option3</option>
                        <option>etc...</option>
</select>
<input type="submit">
</form>

</body>
</html>

 

retrieve.php:

<?php

$selectedoption        = $_POST['select']; 

print"

<html>
<body>
<select id='select' name='select' >
                        <option>option1</option>
                        <option>option2</option>
                        <option>option3</option>
                        <option>etc...</option>
</select>
</body>
</html>
";
?>

 

How do I specify that the select menu in retrieve.php should have the option selected that was chosen from the select menu in send.htm?

 

I'm guessing this is probably quite straightforward, but I can't quite work it out. Please help!

Thanks.

As PaulRyan said, your <option> tags need a name= attribute for the <select> to pass the value properly.

 

I find it easier to build <select>s from an array, especially when making a "sticky" form. Here's a basic demo. It's the same principle as building the <select> from a database query result.

 

echo '<form method="post">';
$select = array(
1 => 'value 1', // starts the indices at 1 instead of 0
'value 2',
'value 3',
'value 4',
'value 5' );

echo '<select name="name">\n';
foreach( $select as $k => $v ) {
   echo "<option value=\"$k\"";
   echo $k == $_POST['name'] ? ' selected="selected"' : ''; // pre-selects the option if the value matches what was submitted
   echo ">$v</option>\n";
   }
echo '</select>';
echo '<input type="submit" value="submit" name="submit"></form>';

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.