I want to have dropdown selected option selected after submit/refresh page. I search for other examples but no one works on my code.
How to retain selected value after submit/refresh with this code?
<form name="test" action="test.php?id=<?php echo $row["id"]; ?>" method="post">
<select id="test_email" name="test_email">
<option value="">...select</option>
<?php
$sql2 = "SELECT test_id, test_email FROM test WHERE status='Act'";
$res = $db->query($sql2);
if ($res->num_rows > 0) {
while($row1 = mysqli_fetch_array($res)) {
?>
<option value="<?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>"><?php echo $row1['test_id'];?></option>
<?php
}
}
?>
</select>
Solved this way:
- Because I could not pass
$_POST['test_email']
with<?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>
- Because I use
explode
on$_POST['test_email']
- I make one more post (insert in db)
$test_temp = trim(mysqli_real_escape_string($db, $_POST['test_email']));
to have my dropdown value (whole string) in db. - I added hidden input in my form
<input id="test_temp" type="hidden" name="test_temp" value="<?php echo $row["test_temp"]; ?>">
- And changed select option line to
<option value="<?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>"<?php if($row1['test_email'] . '-' . $row1['test_id'] == $row['test_temp']) echo ' selected="selected"' ; ?>><?php echo $row1['test_id'];?></option>
.
Perhaps this could be simpler but it works like a charm.
@roberto06: Thank you for your guidance.