I am working on some form coding in PHP, and I have everything working pretty well when JavaScript is enabled. But from past experience and poor experiences with other sites not doing well when JavaScript is disabled, I thought I would pay more attention to it for this current project.
Regarding input type="text" POST fields, this is not a problem. But for the drop-down I happen to be using, I cannot get it to persist. Well, I can, but then the default selection is not correct. Here is some code…
Basic drop-down structure:
<select id="topic" name="topic">
<option value="Select an option">Select an option</option>
<option value="Topic A">Topic A</option>
<option value="Topic B">Topic B</option>
<option value="Topic C">Topic C</option>
</select>
I thought maybe if I blended selected with POST data, I could get it to work like this:
<select id="topic" name="topic">
<option selected="selected" value="Select an option">Select an option</option>
<option value=""><?php echo $_POST['topic']; ?></option>
<option value="Topic A">Topic A</option>
<option value="Topic B">Topic B</option>
<option value="Topic C">Topic C</option>
</select>
But it doesn’t persist; it only goes back to the default, ‘Select an option’.
Trying this didn’t work either:
<select id="topic" name="topic">
<option value="Select an option">Select an option</option>
<option selected="selected" value=""><?php echo $_POST['topic']; ?></option>
<option value="Topic A">Topic A</option>
<option value="Topic B">Topic B</option>
<option value="Topic C">Topic C</option>
</select>
It persists, but doesn’t have the correct default. Starts out blank (because POST is not entered yet).
I have done some Google searches and not really found anything very useful for this kind of thing, so I’m not sure where to go next. Any ideas/suggestions?
Thank you very much in advance!
I normally do something like the following:
What this does is print out the select box just as you’ve described, but it adds a selected=”selected” attribute to the option that matches your $_POST variable.