illadelphiakid Posted October 13, 2011 Share Posted October 13, 2011 I'm trying to get this drop down menu to be sticky once the user clicks submit. Here's my entry code: if (isset($_POST['guess'])) { if ($_POST['guess'] == $_SESSION['number']) { $response = "You Win!"; unset($_SESSION['number']); } else { $_SESSION['tries']++; if ($_SESSION['tries'] < 3) { $response = "Try #{$_SESSION['tries']}<br /><br />"; } else { $response = "You Lose"; unset($_SESSION['number']); } } } if (empty($_SESSION['number'])) { $_SESSION['tries'] = 0; $_SESSION['number'] = rand(1, 10); } And in my body: <select name="guess" id="guess"> <?php for ($i = 1; $i < 11; $i++) { echo "<option value='{$i}'>{$i}</option>"; } ?> </select> Link to comment https://forums.phpfreaks.com/topic/249071-make-selection-list-sticky/ Share on other sites More sharing options...
codefossa Posted October 13, 2011 Share Posted October 13, 2011 Should work. <select name="guess" id="guess"> <?php for ($i = 1; $i < 11; $i++) { $selected = (isset($_POST['guess']) && $_POST['guess'] == $i) ? 'selected="selected"' : ''; echo "<option value='{$i}' {$selected}>{$i}</option>"; } ?> </select> In the future, you should really try to do your work on your own. That was meant to be an example so you could write your own. Link to comment https://forums.phpfreaks.com/topic/249071-make-selection-list-sticky/#findComment-1279146 Share on other sites More sharing options...
Psycho Posted October 13, 2011 Share Posted October 13, 2011 That's the same process I typically use. However. in the interest of efficiency I would not do the isset() test on each iteration of the loop. Just do it once before the loop and set a variable to test against. $selected_guess = (isset($_POST['guess'])) ? : $_POST['guess'] : false; for ($i = 1; $i < 11; $i++) { $selected = ($selected_guess === $i) ? 'selected="selected"' : ''; echo "<option value='{$i}' {$selected}>{$i}</option>"; } Link to comment https://forums.phpfreaks.com/topic/249071-make-selection-list-sticky/#findComment-1279150 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.