February 12, 2010

Rails link_to with prompt instead of confirm

Today I've been asked to create a link to delete record. In Rails it's quite simple to do it, even there is an example on the documentation. For example,

link_to "Delete Me", {:action => "delete_me", :id => @dm.id}, :confirm => "Are you sure?", :method => :delete

This means to pop-up confirm box with message "Are you sure?" after click the link.

But sometimes, we want the user to enter some text first just to make sure the confirmation or to prevent deletion because of wrong selection by user.

So, instead of confirm I use the prompt box that have a text box. But rails don't have the helper/parameter to do it.

Then I make two links, one is for handle the prompt and user input and the other one to handle the request. So the code is become,

link_to_function "Delete Me", "function_that_handle_user_input"

link_to "Delete Me", {:action => "delete_me", :id => @dm.id}, :method => :delete, :style => "display:none"

Yes, the second link is a hidden link. And the prompt box is inside the function that should handle the user input, example

if(prompt('Enter YES to continue') == 'YES'){
  $(this).next().onclick();
}


For the javascript function, you could write based on your need or just use your imagination.

That's it for now and thanks. Just write a comment if there is another solution or if you want to ask me.

1 comment:

  1. This action is like Captcha Deletion, but using javascript() and CsS. Nice trick.

    ReplyDelete