Search code examples
jquerylivepreventdefault

preventDefault does not work with jQuery.live


I have this piece of JS:

$('.self_delete').live('click', function(e){
    e.preventDefault();
    $.ajax({
        type: 'DELETE',
        url: $(this).attr('href'),
        success:  $(this).parent().remove(),
        dataType: "script"
    })
});

which target this HTML:

<a href="/list_items/34" class="self_delete" data-method="delete" rel="nofollow">
    <i class="icon-trash"></i>
</a>

The problem is that when I click on the link, it will first submit the ajax call to the server THEN is send the normal HTML call. Of course, this mess things up since the list_item is already deleted.

I have a feeling this is caused by the live() call, but I cant figure out why. My JS-Fu needs some training!


EDIT changed the code to this:

$('.self_delete').live('click', function(e){
    e.preventDefault();
    var self = $(this);
    $.ajax({
        type: 'DELETE',
        url: self.attr('href'),
        success:  function(){ self.parent().remove() },
        dataType: "script"
    })
});

And I still have the same issue. Tried to replace .live with .on but it did not even try to submit via AJAX, so I guess I will have to read the doc more carefully :-S


Solution

  • You need to wrap your success code in an anonymous function, at the moment it will run immediately, also store a reference to $(this) in another variable e.g self

    $('.self_delete').live('click', function(e){
    e.preventDefault();
    var self = $(this); 
    $.ajax({
        type: 'DELETE',
        url: self.attr('href'),
        success:  function(){ self.parent().remove() }, 
    })
    });
    

    On a side note, you should be using .on as of jQuery 1.7 .live has been deprecated.

    $(document).on('click', '.self_delete', function(e){
        e.preventDefault();
        var self = $(this); 
        $.ajax({
            type: 'DELETE',
            url: self.attr('href'),
            success:  function(){ self.parent().remove() }, 
        })
    });