0

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>

Javascriptを含めることが可能かどうか疑問に思っています。そのため、ユーザーが「ユーザーを無効にする」を選択すると、「このユーザーを無効にしてよろしいですか?」というメッセージが表示されます。浮き出る。提案をお寄せいただきありがとうございます。

4

3 に答える 3

1

ここでの問題は、アラートを表示することではなく (これはかなり単純なことです)、select 要素が以前持っていた値を追跡することです。結局のところ、ユーザーが「いいえ」をクリックしてユーザーが無効になった場合、それはあまり役に立ちません。

これを行うには、非表示の入力要素を使用して元の値を保存するのが最も簡単な方法だと思います。その後、 を参照して、オプションを正しく設定し直すことができます。

このようなもの (ここで修正された HTML 構造、注意してください ;-) ):

<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>
于 2012-05-16T16:10:24.257 に答える
0

この JavaScript はあなたのためにそれを行うべきです:

<select name="Select1" onchange="if(this.value==0) confirm('are you sure you want to disable this user?')">
<option value="1">Chair</option>
<option value="2">SACA</option>
<option value="5">Faculty</option>
<option value="0">Disable user</option>
</select>​​​
于 2012-05-16T16:01:21.200 に答える