How do you make an HTML Select/Drop-down Box “sticky”??
I have an entry form, and all of my text Boxes are “sticky” in case a user makes a mistake and the screen refreshes, but my Select Boxes keep re-setting which is annoying!
This is as much a PHP question as HTML, but my confusion is more so with the HTML syntax and where to put my code.
The third one will now be selected by default when the page loads. You can set whichever one you want to be the selected one with PHP by simply echoing out selected=“selected” in the appropriate <option>.
Okay, right, but I’m not sure how to write the PHP code?! :-/
For my States field, there are - of course - 50 different choices… I’m drawing a blank what code i would need to write to let the Select Box pick up where the user left off on a page refresh?!
If the user reloaded the page that’s their problem. You should only worry about this if they pressed the Submit button and they’ve made a mistake in the filling out of the form. Then you can just use the $_POST array to find out what they submitted, and fill out the form with these values.
<label>Choose A Drink</label>
<select id="drink_choice" name="drink_choice">
<option value="no drink"><?php if (isset($_POST['drink_choice'])) {print "You Chose: $drink_choice";} else {print 'Choose a Drink!';}?></option>
<option value="Tea">Tea</option>
<option value="Coffee">Coffee</option>
<option value="Water">Water</option>
<option value="Beer">Beer</option>
</select>
In this example, before a selection is made the user sees Choose a Drink!, but if an error is made and the user is directed back to the form, they then see displayed the option they chose.
EDIT:
Actually, cancel that. I just tested my code, and it remembers the selection made, but doesn’t then send it on. I’ll have to explore oddz’ solution.
what it does is check post[value] is set or not (if form is posted it will be else no)
if is it set,check if the option was earlier selected one by using ternary operator
$selected=(($_POST[‘value’]==0)) ? ‘Selected’ : “”;
the $selected will be “selected” if it was the one causing value to be selectd again other wise will be empty
so look complicated but is simple…
hope it helps…
downpart:it is static… and own need to do same for each option…
good news:tweak bit more even that may not be required…