Jump to content

Recommended Posts

Is there a simple way to keep a yes or no selection in a drop down menu after the page is submitted?

<form name="survey" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Satisfied<select name="satisfied">
<option value="yes"> yes </option>
<option value="no"> no </option>
</select>
<input name="submit" type="submit" value="Submit">
</form>

 

 

 

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/
Share on other sites

You could do something like:

 

...

<select name="satisfied">
<option value="yes"<?php if($_POST['satisfied'] == 'yes') { echo ' selected="selected"'; } ?>> yes </option>
<option value="no"<?php if($_POST['satisfied'] == 'no') { echo ' selected="selected"'; } ?>> no </option>
</select>

...

 

 

Also, you should avoid using $_SERVER['PHP_SELF'] in forms for security reasons. For more info, see:

http://www.mc2design.com/blog/php_self-safe-alternatives

Or, may be like this:

<form name="survey" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Satisfied<select name="satisfied">
<?php
$satisfied_options = array("yes", "no");
$satisfied_opted = '';
foreach($satisfied_options as &$option) {
  if ( isset($_POST['satisfied']) ) {
    $satisfied_opted = ($_POST['satisfied'] == $option ) ? 'selected' : '';
  }
  echo '<option value="'.$option.'" ' . $satisfied_opted . '>'.$option.'</option>';
}
?>
</select>
<input name="submit" type="submit" value="Submit">
</form>

 

Thanks guys , that worked fine.

Instead of using echo $_SERVER['PHP_SELF'] is it OK to just use the url of the same page the form is on?

 

You can leave the action attribute empty to submit the form in the same page. It is completely valid XHTML and also included in the form submission algorithm of HTML5 (look here, point 9).

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.