I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called “postage” whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks
You almost got it. You need to set the attribute
selected="selected"(the exact form you need technically depends on your HTML doctype, but this is a safe default) on the<option>element if and only if the value of$postageequals the value of the element. So:Note that this violates the DRY principle because you now have two occurrences of the string
"foo"in there, so it’s a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it withforeachto produce the<option>tags.