Alex
Alex

Reputation: 751

How to remember multiple selected options in a select-tag?

I have a <select> with multiple allowed choices at the same time. I want to keep ALL selected values after a form submission. How to do this?

I tried the followig, but this only works for ONE option...

<select multiple name="example" method="POST" action="<? echo $_SERVER['PHP_SELF']?>">
  <option value="optA" <?php if ($_POST['example'] === "optA"){echo 'selected="selected"';} ?>>Option A</option>
  <option value="optB" <?php if ($_POST['example'] === "optB"){echo 'selected="selected"';} ?>>Option B</option>
</select>

Expectedly the following always returns the latest selected option:

<?php if (isset($_POST['example'])){echo $_POST["example"];} ?>

So how can i achieve my goal? Many thx in advance! :)

Upvotes: 0

Views: 948

Answers (1)

Tibor B.
Tibor B.

Reputation: 1690

Use an array as the POST variable, like this:

<select multiple name="example[]">
  // options
</select>

And retrieve them like so:

print_r($_POST['example']);

I would suggest storing your option values and names in an array as well, so it's easier to handle:

$options = array(
  array(
    'value' => 0,
    'name'  => 'A'
  ),
  array(
    'value' => 1,
    'name'  => 'B'
  ),
  array(
    'value' => 2,
    'name'  => 'C'
  ),
  array(
    'value' => 3,
    'name'  => 'D'
  )
);

Then just simply create your select options, using a foreach loop, and check if the current option is in your post variable:

<select multiple name="example[]">
  <?php foreach ($options as $option) { ?>
  <option value="<?php echo $option['value']; ?>"<?php echo (isset($_POST['example']) && in_array($option['value'], $_POST['example'])) ? ' selected="selected"' : ''; ?>><?php echo $option['name']; ?></option>
  <?php } ?>
</select>

Upvotes: 2

Related Questions