Reputation: 11
Here is a little code snippet that works somewhat well but not quite what I am trying to achieve:
<html>
<head>
</head>
<body>
<form method='post'>
Display
<select name="displayOptions" onchange="this.form.submit()">
<option selected value="all">all</option>
<option value="open">open</option>
<option value="reserved">reserved</option>
<option value="blocked">blocked</option>
</select> computers
</form>
<?php
if(isset($_POST["displayOptions"])){
if ($_POST["displayOptions"]=='all')
allFunction();
if ($_POST["displayOptions"]=='open')
openFunction();
etc...
}
?>
</body>
</html>
As soon as the user chooses a dropdown selection I want the action to take place. I also want the default action to be "all" and for that to happen as soon as the form is loaded. The code snippet above works well with the exception of 2 things.
As I typed this out I have a feeling I can tackle #2 with a $_SESSION variable but I am still stumped why the first option in the select dropdown is not registering.
Upvotes: 1
Views: 375
Reputation: 1193
As pointed out by Funk, you may want to look into ajax calls instead to avoid reloading the page when selecting something (which is arguably a poor user experience), but if you insist on using the same structure, you may do this:
<?php
// Set the option selected ("all" by default)
$option_selected = !empty($_POST["displayOptions"])? $_POST["displayOptions"] : "all";
?>
...
<select name="displayOptions" onchange="this.form.submit()">
<option value="all" <?php if ($option_selected == "all") echo "selected" ?>>all</option>
<option value="open" <?php if ($option_selected == "open") echo "selected" ?>>open</option>
<option value="reserved" <?php if ($option_selected == "reserved") echo "selected" ?>>reserved</option>
<option value="blocked" <?php if ($option_selected == "blocked") echo "selected" ?>>blocked</option>
</select>
...
<?php
if ($option_selected == "all")
allFunction();
else if ($option_selected == "open")
openFunction();
etc...
?>
I haven't tested it but it should work fine.
Upvotes: 1