Felipe Ch.
Felipe Ch.

Reputation: 137

jQuery .click() function only works once with $(window).load()

I've been trying to make a list with a delete button to delete an element (using ajax). When the element is deleted, I use $("#tableId").load(window.load + " #tableId); to update my table so the deleted element disappears, This works fine the first time, but when I delete an element for the first time and #tableId is loaded, I can't remove more items.

Here is the script:

$(".remove").click(function(){
    $("#message").show();
    $("#message").html("Entro!");
    var id = $(this).attr("value");
    var href = $(this).attr("href");
    var tipo = href.replace(/([^a-zA-Z0-9])+/g, '');
    $.ajax({
        url: 'inc/checkRemoverObjeto.php',
        type: "POST",
        data: 'tipo='+tipo+'&&id='+id,
        success: function(response){
            $("#message").show();
            $("#message").html(response);

            $("#tableId").load(window.location + " #tableId");
        }
    });
    return false;
});

I searched but I could'nt find a solution. Thank you !

Upvotes: 2

Views: 1253

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

Use event delegation with document and on() like

$(document).on('click', '.remove', function(){...});

This will attach the event handler to all current and future .remove elements

Upvotes: 2

Tushar
Tushar

Reputation: 87203

You need to use event delegation using on. This will apply the events to the dynamically added elements inside the #tableId.

$("#tableId").on("click", ".remove", function() {
    // Your code here
});

Upvotes: 3

Related Questions