I am trying that once an option is selected in a select
, when submitting the form that option is kept selected. I am trying to implement it on this simple example:
<?php
$valores=array(1=>"opcion 1", "opcion 2", "opcion 3");
?>
<form action="" method="POST">
<select name="Select">
<option value='0'>Seleccionar opcion</option>
<?php
foreach($valores as $key=>$value)
{
if($_POST["Select"]==$key)
{
echo "<option value='".$key."' selected>".$value."</option>";
}else{
echo "<option value='".$key."'>".$value."</option>";
}
}
?>
</select>
<input type="submit" value="enviar">
</form>
The previous example works correctly and when trying to implement it on my code I can't get it to work correctly, this is what I have written:
echo "<form action='' method='POST'>
<select name='selec'>
<option value='0'>Selecciona opcion</option>";
// Lista los directorios
$directorio = opendir("adminUser/"); // Ruta Directorios
while ($ad = readdir($directorio)) {
if(is_dir($ad)) {
} else {
$valores = array(1=>"" . $ad . "");
foreach($valores as $key=>$value) {
// Si coincide lo enviado con el valor
if($_POST["selec"] == $key) {
echo "<option value='".$key."' selected>".$value."</option>";
} else {
echo "<option value='".$key."'>".$value."</option>";
}
}
}
}
echo "</select>
<input type='submit' value='enviar'>
</form>";
The issue is that it option
select
does its function correctly, it shows the names of the directories but when submitting the form it is not able to keep the option selected. Is it because I'm blocked and I can't see where I'm failing?
As a personal tip, avoid using HTML inside PHP. Then, answering your query, the error is that all the folders had the same ID
$valores = array(1=>"" . $ad . "");
. It was necessary to add a counter variable that increases with the while. Here is the modified code: