nanjero05 nanjero05 - 7 months ago 18
PHP Question

PHP - How can i maintain value of a select element after a postback?

I currently have this select:

<select name="state" id="state" selected="<?php echo $state; ?>">
<option value="--">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
</select>


this is the php related to $state:

<?php
$state = "";
$state = $_POST["state"];
?>


since i am not running any validation on it i simply want to retain its value after postback.

Answer

The options are selectable...

Try this:

<select name="state" id="state">
    <option value="--">--</option>
    <option value="ACT"<?php if ($state=="ACT"){echo " selected";} ?>>ACT</option>
    <option value="NSW"<?php if ($state=="NSW"){echo " selected";} ?>>NSW</option>
    <option value="NT"<?php if ($state=="NT"){echo " selected";} ?>>NT</option>
</select>