I am doing an dropdown box, where I have let's say we have "option1" and "option2", the dropbox selects(marks) the "option1" and then we select the "option2", I want it to mark the "option2" in the dropdown box, but it doesn't mark it.
I'm trying to avoid to do javascript on this one, so I wonder if I can do it only on PHP.
Advices? Thanks!
Edit. Well the problem is that i dont know how many options i have before building the dropdown menu. I get an array generated from a table in a database and make the options based on that. Code:
<select name="department">
<?php foreach(bloggModelControler::getDepartments($_SESSION['user']) as $tempDepartment){
if(strcmp($tempDepartment, $department) == 0){
$selected = ".selected='selected'.";
}else{
$selected = ".selected=''.";
}
$dropdown = "<option \"$selected\" value=\"$tempDepartment\">\"$tempDepartment\" Selected</option>";
echo $dropdown;
}?>
</select>
and $department:
<?php
if(isset($_POST['department'])){
$department = $_POST['department'];
}else{
$departments = bloggModelControler::getDepartments($_SESSION['user']);
$department = $departments[0];
}
?>
Updated answer based on updated question (included code)
Don't put the periods inside the text variables for 'selected'.
if(strcmp($tempDepartment, $department) == 0){
$selected = "selected='selected'";
}else{
$selected = "selected=''";
}
Previous answer
In your PHP code that generates the HTML for the Select box, you have to specify which option is selected.
For example:
<select name="selectbox">
<option <?php if ($_POST['selectbox'] == 'option1') echo 'selected="selected"';?>>option1</option>
<option <?php if ($_POST['selectbox'] == 'option2') echo 'selected="selected"';?>>option2</option>
</selected>
Alternate syntax:
<select name="selectbox">
<option <?= ($_POST['selectbox'] == 'option1')? 'selected="selected"' : '';?>>option1</option>
<option <?= ($_POST['selectbox'] == 'option2')? 'selected="selected"' : '';?>>option2</option>
</selected>