1

I have a table, each row assigned a unique ID so I can click on the row, grab it with jquery and edit the data for that row. I like clicking on the entire row for convenience and it makes it easier for the user..

In the last column, I have an X which I want to be able to click on to delete that row. Again, it has a unique ID so I can identify each row. My jquery looks something like this..

    $('.delrow').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('id');
    id = id.substr(3);
    if (confirm('Are you sure you want to delete this row?')) {
        $.ajax({
            url: "/rowdelete/?delid="+id,
            success: function(data) 
            {
                location.href="/";
            }
        });
    } else {
        return false;
    }   

});

This should delete the row then return to the homepage. What it does is delete the row then continue on into my edit module with a row id of null since the default action for the row click was to do exactly that. I presume at this point that preventDefault only applies to form actions and thus, won't work in this instance. How can I override the default row click action?

Thanks!

Doug Wolfgram
  • 2,064
  • 4
  • 27
  • 42

2 Answers2

2

Instead of e.preventDefault(), use e.stopPropagation(). Easy.

Edit: Now that I'm not using my phone to answer, I thought I'd add a bit more. Stopping propagation might have undesired effects further down the line. For example, what if you want to add an event to $(window).click()? Having stopped propagation, this event won't be fired if the user clicks the x. An IMO better way is somethink like this:

$('.row').click(function (event) {
    if ($(event.target).hasClass('delrow')) {
        return false;
    }
    // edit row
});

Then you can either add you're event to the x element. You could also put your event in the if statement if you prefer... it's a matter of preference.

Nathan MacInnes
  • 11,033
  • 4
  • 35
  • 50
1

It looks like you want to prevent other event handlers from occuring so you want either event.stopImmediatePropagation() or event.stopPropagation().

http://api.jquery.com/event.stopImmediatePropagation/
http://api.jquery.com/event.stopPropagation/

This link may clarify a bit: event.preventDefault() vs. return false

Community
  • 1
  • 1
jholloman
  • 1,959
  • 14
  • 16