I am working on a PHP form today and I need some help with the <select> & <option> tags. What I want to do is take a value from $_GET that is already in the <option> list and have it display as the index. The way my form works is that a user selects a location and hits an update button. When the page submits, it sends the value through $_GET and then uses it to grab the correct info from a database. After looking at said info, they have the option to delete it which is where I would need it. The issue is they have to reselect the location in order to delete it. I need the value to stay selected.
For example, say the user clicks on NJ in the selection box and hits update. The page would submit and ,lets say, reviews for restaurants are displayed. I want the selection box to keep the value of NJ until the user changes it.
My quick fix was to use the following code at the beginning of the <option> list:
<?php
if($_GET['chooseLocation'])
echo "<option>$_GET['chooseLocation']</option>";
?>
The only downside to this is that it would show NJ twice.
1) Am I on the right track?
2) Since I am using $_GET and storing the info in the URL, should I use javascript to do this instead?
I looked through about 15 questions and none of them answered my question. If you think this is a repost or copy, please post the original in the comments so I can see it.
I don’t know your entire code, only that little piece. The way I usually do this is by the
selectedattribute and with some sort of IDs of my items. I guess you are reading the information from a database and the information you maintain from page to page is the value of the option. I do something like this:Alternatively you can assume that virtually every user has JavaScript nowadays. Thus you actually could do the same with JavaScript by “attaching” the
selectedattribute on DOM readiness or when the page has loaded (e.g. using jQuery). Of course there is still a minority that refuses to use JavaScript, but I have no statistics up right now.