这里的问题不是显示警报——这相当简单——而是跟踪选择元素曾经拥有的值。毕竟,如果用户单击“否”并且用户无论如何都被禁用,那将没有多大用处。
为了做到这一点,我建议最简单的做法是使用隐藏的输入元素来存储原始值。然后,您可以参考以正确设置选项。
像这样的东西(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>