Jump to content

keep yes or no selection?


garyed

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).

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.