I have this function that generates a drop-down list and makes the option that was saved before the one that is automatically selected on the page. Thus, if in a drop down list of 'Male' and 'Female' you chose Female, the next time you go to that page, Female is selected already since that was your choice before.
To do that, I use the 'selected' attribute in the <option> tag.
I am going to show you a bit of a code segment below from a while loop that goes through all the options in the dropdown list (retrieved from a db). $x is the dropdown list option, and $variable is the option chosen by the user before.
So as you can see below, if the option matches the one the user last selected, then we echo an option with the selected attribute. STRANGELY ENOUGH, that option is not selected at all...the first option in the list is selected for some reason. To see if I was even getting to the else clause where the selected attribute was, I added the word 'selected' to the option that should have been selected.
INDEED, the dropdown list showed the word 'selected' appended to the option I had last chosen, meaning that option had the 'selected' attribute. But it didnt' choose it.
if($x != $variable) {
echo "<option value='$x'>$x</option>";
}
else {
?>
<option value="<?php echo "$x"; ?>" selected><?php echo "$x selected"; ?></option>
<?php
}
Can anyone explain why? BTW the $x is retrieved from a list of options that are separated by new lines...in the db, it shows them as separated by \r\n, and I use explode with \r\n to separate the options...I don't know if that matters or not