Run jQuery function in dynamically generated table after an AJAX

Asked

Viewed 501 times

3

I need to execute the function below, after the AJAX request it has to remove the row from the table, if I put the code that removes the direct line in the function it removes the line normally, but if I put inside the Success of AJAX it does not remove the line and runs the alert usually in the end.

$('#tabelaMaterial').on('click', '.icon-remove', function (event) {
    $.ajax({
        url: "/RCM/RemoveItemCarrinho",
        type: "POST",
        success: function () {
            $(this).closest('tr').remove();
            alert("Material removido!");
        }
    })
})

1 answer

6


It is a matter of scope, the this down in the success is something else:

$('#tabelaMaterial').on('click', '.icon-remove', function (event) {
    var $this = $(this);
    $.ajax({
        url: "/RCM/RemoveItemCarrinho",
        type: "POST",
        success: function () {
            $this.closest('tr').remove();
        }
    });
});

Related: What’s the difference between $(this) and $this and this?

  • 1

    It worked right, thank you very much.

  • 1

    @Alan, I added an important link to the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.