简体   繁体   中英

How to remove jQuery element added by .append()?

General info
I'm working on a intranet based administration system for a distribution centre.

Situation
Basicly I have a contenteditable table with all user data. Except for the passwords of course. You could compare it with a webbased Excel sheet. Using a jQuery UI dialog, I'm popping op a form that allows the admin (company manager) of the system to change the employees passwords if clicked on a button.

To make sure the password change will be applied to the correct user, I'm passing along the used id to my function that pops up the dialog. Using .append() I'm adding this id to the form. Up to this point everything works perfectly fine.

Problem
If the password change is cancelled, the id must be removed from the form again. Otherwise you end up appending more and more ids to the form on each user clicked. The same goes for when the password change is succeeded. I've tried doing this with jQuery .remove() , but it doesn't seem to work, even though I can't find any issue with the code.

Code

function changePass(id){
    var addID = $("<input>")
        .attr("type", "text")
        .attr("id", "userid")
        .attr("name", "userid").val(id);
    $('#passChangeForm').append($(addID));
    $("#changePass").dialog({
        modal: true,
        resizable: false,
        title: "Change password",
        buttons: [
            {
                text: "Cancel",
                click: function() {
                    $("#passChangeForm").remove("#userid");
                    $(this).dialog("close");
                }
            },
            {
                text: "Ok",
                click: function() {
                    $("#passChangeForm").submit();
                }
            }
        ]
    });
}

$("#passChangeForm").on("submit", function(e){
    e.preventDefault();
    var password = document.getElementById("chPass1").value;
    var password2 = document.getElementById("chPass2").value;
    var userid = document.getElementById("userid").value;
    $.ajax({
        url: "system/changepass.php",
        type: "POST",
        data:'pass1='+password+'&pass2='+password2+'&id='+userid,
        success: function(text){
            alert(text);
            $("#passChangeForm").remove("#userid");
            $("#changePass").dialog("close");
        }
    });
});

只需使用:

$( "#userid" ).remove();

Change the line

$("#passChangeForm").remove("#userid");

to

$("#userid").remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM