PHP drop-down menu with Javascript alert

advertisements

I have created a simple drop-down menu in PHP:

<td> Privilege: </td>
<td><select name="privilege">
<?php
    $position_list = array(
                1 => "Chair",
                2 => "SACA",
                5 => "Faculty",
                0 => "Disable User",
                );
    foreach ($position_list as $priv_id=>$position) {
    echo "<option value= \"{$priv_id}\"";
            if ($priv_id == $sel_user['privilege']) {
                 echo " selected";
            }
            echo ">{$position}</option>";
    }
?></td></select>
        </tr>
        </tr>

I am wondering if it is possible to include some Javascript. So, when the user selects "Disable User", a message saying "are you sure you want to disable this user?" pops up. Thanks in advance for any suggestions!


The problem here is not displaying the alert - that's fairly simple - but keeping track of the value the select element used to have. After all, it wouldn't be much use if the user clicked "no" and the user was disabled anyway.

In order to do this, I suggest the easiest thing to do would be to use a hidden input element to store the original value. You can then refer to the to set the options back correctly.

Something like this (HTML structure corrected here, please pay attention ;-) ):

<td>Privilege:</td>
<td>
  <!-- note the onchange event -->
  <select name="privilege" onchange="checkDisable(this);">
<?php 

    // Define the options
    $position_list = array(
      1 => "Chair",
      2 => "SACA",
      5 => "Faculty",
      0 => "Disable User",
    );

    // Create the list
    foreach ($position_list as $priv_id=>$position) {
      echo "<option value= \"{$priv_id}\"";
      if ($priv_id == $sel_user['privilege']) {
        echo " selected=\"selected\"";
      }
      echo ">{$position}</option>";
    }   

?></select>
  <input type="hidden" id="privilege_old_val" value="<?php echo $sel_user['privilege']; ?>" />
  <script type="text/javascript">
    function checkDisable(element) {

      // Firstly check if the user selected the disable option, then get them to confirm it
      if (element.options[element.selectedIndex].value == 0 && !confirm("Are you sure you want to disable this user?")) {
        // If they didn't confirm it, loop the options...
        for (var i = 0; i < element.options.length; i++) {
          // Find the option with the old value...
          if (element.options[i].value == document.getElementById('privilege_old_val').value) {
            // ...and set the select back to that option
            element.selectedIndex = i;
          } // if
        } // for
      } // if

      // Update the input that tracks the old value with the current value
      document.getElementById('privilege_old_val').value = element.options[element.selectedIndex].value;

    }
  </script>
</td>