garyed Posted May 18, 2011 Share Posted May 18, 2011 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> Quote Link to comment https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/ Share on other sites More sharing options...
cyberRobot Posted May 18, 2011 Share Posted May 18, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/#findComment-1216963 Share on other sites More sharing options...
anupamsaha Posted May 18, 2011 Share Posted May 18, 2011 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> Quote Link to comment https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/#findComment-1216967 Share on other sites More sharing options...
garyed Posted May 18, 2011 Author Share Posted May 18, 2011 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? Quote Link to comment https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/#findComment-1217005 Share on other sites More sharing options...
Fadion Posted May 18, 2011 Share Posted May 18, 2011 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). Quote Link to comment https://forums.phpfreaks.com/topic/236735-keep-yes-or-no-selection/#findComment-1217011 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.