Skip to content

Instantly share code, notes, and snippets.

@tamouse
Created February 19, 2013 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/4982630 to your computer and use it in GitHub Desktop.
Save tamouse/4982630 to your computer and use it in GitHub Desktop.
PHP snippet to show how to handle multiple select, maintaining select options.
<?php
// Initial value for demo
$DPRpriority = array(array('name' => "Crimes Against Persons", 'selected' => false),
array('name' => "Disturbances", 'selected' => false),
array('name' => "Assistance / Medical", 'selected' => false),
array('name' => "Crimes Against Property", 'selected' => false),
array('name' => "Accidents / Traffic Problems", 'selected' => false),
array('name' => "Suspicious Circumstances", 'selected' => false),
array('name' => "Morality / Drugs", 'selected' => false),
array('name' => "Miscellaneous Service", 'selected' => false),
array('name' =>"Alarms", 'selected' => false));
echo "<h1>Initial value of DPRpriority:</h1><ul>\n";
foreach ($DPRpriority as $item => $value) {
echo "<li> ".$item.": ".$value['name']." selected: ".$value['selected']." </li>\n";
}
echo "</ul>\n";
if (count($_POST) > 0) {
// something was posted:
echo "<h1>\$_POST:</h1><pre><code>\n";
var_dump($_POST);
echo "</code></pre>\n";
echo "<h2>Items selected:</h2><ul>\n";
foreach ($_POST['DPRType'] as $item) {
$DPRpriority[$item]['selected'] = true;
echo "<li>".$item.": ".$DPRpriority[$item]['name']."</li>\n";
}
echo "</ul>\n";
echo "<h1>Final value of DPRpriority:</h1><ul>\n";
foreach ($DPRpriority as $item => $value) {
echo "<li> ".$item.": ".$value['name']." selected: ".$value['selected']." </li>\n";
}
echo "</ul>\n";
}
?>
<form method="post">
<select name="DPRType[]" id="DPRType[]" multiple onchange="" size="<?php echo count($DPRpriority) ?>">
<?php foreach ($DPRpriority as $index => $value) { ?>
<option value="<?php echo $index; ?>"<?php if ($value['selected']) {echo ' selected="selected"';} ?>><?php echo $value['name'];?></option>
<?php } ?>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment