JavaScript Confirmation Dialog For a Simple HTML Form
As I might have mentioned a few times before, one of the downsides of doing my project in Sinatra is that I miss out on some of the great Rails helpers, like a simple link_to delete with a confirmation dialog:
<%= link_to 'Delete this task', task_url(@task), :confirm => 'Are you sure?', :method => :delete %>
In order to accomplish this same task in Sinatra I’m actually making a form that includes the information necessary to delete the specific task:
<form method="post" action="/tasks/<%= @task.id">
<input type="hidden" name="_method" value="delete">
<button type="submit">Delete this task</button>
</form>
For the past week I’ve wanted to add a confirmation dialog to this form so that a user is prompted if they really want to delete the task, and whenever I looked for a quick fix I was stumped. So while on vacation I started reading about the basics of JavaScript (which I needed to do anyway) and I was still surprised that with all the things I was learning I still couldn’t get my confirm dialog to act the way that I wanted. I had no problem getting it to appear and do all sorts of cool behaviors, but there wasn’t a simple way to abort the request to the delete method if a user hit “cancel”.
…and it’s great to be back in the office. I was sitting next to Jeremy today so after I helped him talk through some perplexing test behavior I asked him if he knew an easy way to implement a JavaScript confirm dialog. He wasn’t entirely sure how to intercept the request either but he did know exactly what to Google. Within a minute or two we happened across the handy little onsubmit
addition to my form:
<form onsubmit="return confirm('Are you sure you want to delete?');" method="post" action="/tasks/<%= @task.id">
<input type="hidden" name="_method" value="delete">
<button type="submit">Delete</button>
</form>
And that’s it. No other code required.
Thanks, Jeremy.