flyer88
flyer88

Reputation: 1093

Create a custom jquery confirm dialog when clicking a link_to with method delete in rails

how are you? I'm facing the following problem in rails 2.3.

In a view I'm rendering an anchor with the link_to helper with method :delete, i.e.:

link_to "DELETE!", resource_path(@resource), :method => :delete

This works beautifully! But I want to span a confirm dialog before proceding with the destroy action. I could do this with the built-in confirm option:

link_to "DELETE!", resource_path(@resource), {:method => :delete, :confirm=> "Are you sure?"

But I don't like this dialog style.

I want a custom dialog generated by the jquery dialog. Thus I bind a click event on that link that span the confirm dialog I wanted.

The big problem is that when the user clicks the link, the confirm dialog appears but the delete request is executed regardless the OK or CANCEL button is pressed. Inspecting the rendered link I remember that rails adds an onclick event over that link that generates the corresponding hidden form with _method: delete, etc, etc, etc.

One solution is to make the AJAX delete request in the javascript function when the user clicks the OK button. However this approach will introduce some problems, I prefer not to do that.

So what do you suggest in this situation? Is there a way to establish event order? I mean, capture first the event that spans the confirm dialog and depending on that unbind or cancel the future events?

Thanks

Upvotes: 2

Views: 1878

Answers (1)

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

You have to return the value of confirm (true/false) to the click event of the link. If the click returns false, then the browser will not follow the link.

Taken from this answer on SO:

:onclick => "return confirm( message )"

It's not the jQuery dialog, but it will get your the correct functionality.

Upvotes: 2

Related Questions