Search code examples
jqueryreload

jQuery doesnt work after adding a jquery line


I have few line that listing to this script

$("a.remove").click(function(){
    var id = $(this).attr('id')
    var user = $(this).attr('value')
    $.ajax({
        success : function(){
            var url = "includes/action.php?page=access&action=remove";
            var popupmessage = "Error";
            $.post(url, { id: id },
                function(data){
                    return true;
            });
        }
    });
});

but when i add new line via jQuery it doesn't work until refreshing the page

$("<a class=\"remove\" href=\"#\"></a>").insertAfter('#accesstable tr:last');

any idea how to fix it ?

Edit: Working code

$('a.remove').live('click', function(){
    var id = $(this).attr('id')
    var user = $(this).attr('value')
    $.ajax({
        success : function(){
            var url = "includes/action.php?page=access&action=remove";
            var popupmessage = "Error";
            $.post(url, { id: id },
                function(data){
                    return true;
            });
        }
    });
});

Solution

  • If you mean that your newly added anchor tag doesn't call the same click event that you have already declared, that is because you are using the .click() function. This only adds the click event to those matching elements that are currently in the page.

    You should look at using the live() event, as this will

    Attach an event handler for all elements which match the current selector, now and in the future.

    So you can change to something like:

    $("a.remove").live('click', function(){ .. });
    

    Edit

    Live() is deprecated, you should now use the on() function.