从jquery生成的select下拉列表中删除一个选项

时间:2014-03-11 13:45:04

标签: javascript php jquery select

我正在研究社交网络的一个非常基本的管理员功能,我遇到了这个问题,即我无法从之前使用jquery生成的选择下拉列表中删除选项。下拉列表包含社交网络的所有用户。管理员在单击“删除帐户”时会从数据库中删除相应的记录。

现在的问题是 - 当我点击“删除帐户”时,它工作得非常好,但是带有用户名的选项仍然存在于下拉列表中并且可以被选中 - 当被选中时它显然会返回数十个PHP警告和错误,因为记录不再存在于数据库中。如何立即删除此选项?我尝试了类似下面的内容,但它不起作用。

admin_panel.php (仅限相关内容)

<select name='users' id='users'>
        <option value="" disabled selected>Select user</option>
        <?php
            $sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
                $userList = [];
                while($row=mysql_fetch_assoc($sql)){
                    $username = $row['username'];
                    $userID = $row['id'];
                    $userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
                }
            echo $userList;
        ?>
    </select></br></br></div>
    <div id="user_info">
        <!-- generated user info table-->
    </div>

<script type="text/javascript">
 "$('#user_info').on('click', '#deleteAccount', function(e){
    data.command = 'deleteAccount'
    data.userID = $('#users').val()
    $.post(theURL, data, function(result){
        //Do what you want with the response.
        $('#delete_account_success').html(result);
    })
    $("#users option[value='data.userID']").remove();
    $('#delete_account_success').show();
    $('#delete_account_success').fadeOut(5000);
})
</script>

processUser.php (转换语句的一部分)

if(isset($_POST['command'])){
    $cmd = $_POST['command'];
    $userID = $_POST['userID'];


$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
    $userData['userid'] = $row['id'];
    $userData['username'] = $row['username'];
    $userData['name'] = $row['name'];
    $userData['date'] = $row['date'];
    $userData['email'] = $row['email'];
    $userData['avatar'] = $row['avatar'];
    $userData['about'] = $row['about'];
    $userData['admin'] = $row['admin'];
}
 switch($cmd){
 case 'deleteAccount':
        $sql= "DELETE FROM users WHERE id =".$userID;
        $result=mysql_query($sql);
        echo "<img src='pics/ok.png' class='admin_updated_ok'>";
    break;
}

1 个答案:

答案 0 :(得分:0)

在这一行

$("#users option[value='data.userID']").remove();

您要从#users删除任何选项,其值等于字符串文字data.userID

尝试将其更改为

$("#users option[value='" + data.userID + "']").remove();