Detecting Removed Element After Confirm Dialog Is Used [jquery]

While building an add-on for a WordPress plugin, I ran into a little javascript puzzle. I needed to perform an action straight after a table row was removed by a user. At first I tried binding an event handler to the button that deletes the row using the click event. This would normally work just fine, except the plugin was calling a confirmation dialog. When the javascript functions alert or confirm are called, it brings up a dialog box. At this point a user can choose to cancel the action. If you attach an event handler to the click event of the delete button, it will fire, but it won’t know if the user confirmed or not. In other words, this method was not going to work.

As the plugin was using jQuery’s remove() function to remove the table row, it’s possible to watch for the ‘remove’ event. This event handler isn’t widely documented yet at the time of writing. It should trigger when the selected element is removed from the DOM using jQuery’s remove() method. At first I tried to apply the event handler to table row using On() method with the ‘remove’ event. For some reason this wasn’t triggering after deleting a table row. So, the next method I tried was to bind a ‘remove’ event handler using the bind() method whenever the delete button for the row gets pressed. This does work, but you’ll need to use a recent jQuery version with jQuery UI 1.9+, specifically the jQuery UI widgets component.

And here’s an example:

Leave a Reply

Your email address will not be published. Required fields are marked *