Hi guys,
I have this multiple select box I’ve been working on for 5 hours now and I got everything to work except for one thing.
I can’t seem to get the chosen values to retain in the select box after form is submitted.
I tried looking for the answer on the web but the examples they give there are too complicated. I also tried using the foreach function but that only echos out the chosen countries without selecting them.
Can someone give me advice on how to do this please?
The code:
<form action="register-me.php" method="post">
<select name="inputcountry[]" class="month" size=3 multiple>
<?php
$countries=$_POST['inputcountry'];
foreach ($countries as $country)
echo "<option>$country</option>";
?>
<option value="Europe" class="one">Europe</option>
<option value="---">--</option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
<option value="Austria">Austria</option>
<selected>
You need to add the selected=“selected” to the options.
Here is a quick example:
<?php
$countryArray = array("Alaska", "Arkansas", "Arizona", "Argentina", "Brazil", "Chile");
?>
<form action="#" method="post">
<select name="multi[]" size="3" multiple>
<?php
foreach( $countryArray as $c ) {
$selected = in_array($c, $_POST['multi'])
? ' selected="selected"'
: '';
echo '<option value="'.$c.'" '.$selected.'>'.$c.'</option>';
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Thanks centered effect it worked.
So to see if theoretically I got it. This boolean is actually saying:
If $c is within the posted array, then $selected equals selected. But if it’s not within the array, then $selected equals nothing (’ '). And then echo out the selected value.
Is that correct? Am I understanding it correctly?
Hey adamschroeder,
It’s probably just a typo but in the code you posted you’re trying to close the select element with <selected>. It should be </select>.
Thanks Farid,
luckily I used a different script so this typo was not an issue. But thanks anyway.