问题
I have several links on one page which all direct to the same page, but each of them passes a different variable in the URL (http://sitename.com/thispage.php?id=3). I set new variables to true or false depending on which value is passed for "id", then put the true/false variables in to set the default option on an option tag like so:
if (isset($_GET['id']))
$id = ($_GET['id']);
if ($id = 4)
$id4 = true;
else
$id4 = false;
...
<option value="Value" selected="<?php echo "$id4"; ?>">
Value
</option>
Excuse me if it seems messy.
I've got 12 of those setup, one for each menu option. I can't seem to get it to display the correct one as the default selection though, as it always selects the 2nd to last menu item.
回答1:
One thing you should correct is putting true and false in quotation marks, otherwise they will be converted from boolean to string and end up as a 1 or 0.
Or you could replace the whole thing with this
<option<?php if (isset($_GET['id']) && $_GET['id'] == 4){ echo ' selected'; } ?>>
value
</option>
来源:https://stackoverflow.com/questions/7808402/dynamic-default-selection-for-a-drop-down-menu-using-url-variables