cursesNOOB
cursesNOOB

Reputation: 11

Execute function on dropdown menu change in PHP

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.

  1. 'all' is selected by default (Working As Intended), however allFunction() doesn't run. Even if you select another option and then select 'all' again, 'all' still doesn't work. I would like the allFunction to run as soon as this form loads up with 'all' selected and, of course, to be able to choose 'all' again later.
  2. Whenever a different selection is selected, it loads the correct function (WAI), however the dropdown turns back to all. I know why it does this (becuase the page is being reloaded and 'all' is the default selected value), but I'd like it to stay on the selected option!

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

Answers (1)

Will
Will

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

Related Questions