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.

Link to comment
Share on other sites

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>';

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.