Conservar el elemento seleccionado del menú desplegable después de enviar

Hello I have a dropdown menu which holds items from my database when the submit button is pressed the menu item is not retained instead it resets back to what it started initially.

I read a couple of posts about the subject but my case is specific I am not sure where I should insert the selected attribute.

<form name="upServForm"  action="" method="post" >

<?php
        $dropdown = "<select name='codes'>";
        while($row = mysql_fetch_assoc($result2)) 
        {
            $dropdown .= "\r\n<option value='{$row['sid']}'>{$row['sid']}</option>";
        }
        $dropdown .= "\r\n</select>";
?>

preguntado el 22 de septiembre de 13 a las 04:09

1 Respuestas

prueba esto:

$dropdown = "<select name='codes'>";
while($row = mysql_fetch_assoc($result2)) 
{
    $dropdown .= "\r\n<option value='{$row['sid']}'".(($_POST["codes"] == $row["sid"]) ? " selected='selected'" : "").">{$row['sid']}</option>";
}
$dropdown .= "\r\n</select>";

Respondido el 22 de Septiembre de 13 a las 05:09

there seems to be a missing bracket in your code that closes the one after selected not sure where it goes - Kayoti

thank you though turns out the proper way of doing it is this<?php echo "<select name='codes'>"; while($row = mysql_fetch_array($result2)) { if($_POST['codes']==$row['sid']) { echo "<option selected>".$row['sid']."</option>"; } else { echo "<option>".$row['sid']."</option>"; } } echo "</select>"; ?> - Kayoti

yes - there is a missing bracket in my soltion, but it does work. It uses an inline if statement, to remove the need for duplication of code. - Zack Newsham

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.