Skip to content

Instantly share code, notes, and snippets.

@trey
Created February 8, 2012 05:12
Show Gist options
  • Save trey/1765619 to your computer and use it in GitHub Desktop.
Save trey/1765619 to your computer and use it in GitHub Desktop.
A nice delete confirmation modal in Rails courtesy of Bootstrap

Here's what you get.

Some JavaScript

// Delete confirmation modals
$('#delete-confirm').on('show', function() {
  var $submit = $(this).find('.btn-danger'),
      href = $submit.attr('href');
  $submit.attr('href', href.replace('pony', $(this).data('id')));
});

$('.delete-confirm').click(function(e) {
  e.preventDefault();
  $('#delete-confirm').data('id', $(this).data('id')).modal('show');
});

Some HTML

<div class="modal fade" id="delete-confirm">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Delete this thing?</h3>
  </div>
  <div class="modal-body">
    <p>Be certain, sonny.</p>
  </div>
  <div class="modal-footer">
    <%= link_to 'Delete', something_path+'/pony', method: :delete, :class => 'btn btn-danger' %>
    <a href="#" data-dismiss="modal" class="btn">Cancel</a>
  </div>
</div>

A well-crafted link:

<a href="#delete-confirm" data-id="<%= @something.id %>" class="delete-confirm btn btn-danger"><i class="icon-trash icon-white"></i></a>
@postpostmodern
Copy link

This is a great idea. I sorta modified it to make it easier to drop into any Rails (3.1+) app.

https://gist.github.com/1862479

@trey
Copy link
Author

trey commented Feb 20, 2012

Much better. Thanks, @postpostmodern!

@trey
Copy link
Author

trey commented Dec 5, 2012

This is a Solutions Log post.

@piousbox
Copy link

piousbox commented Apr 1, 2013

No need to add extra anything, Rails already has this functionality:

<%= button_to 'Delete', whatever_path(whatever.id), :method => :delete, :confirm => 'Are you sure?' %>

@vjt
Copy link

vjt commented Jul 2, 2013

@piousbox yes, but by default it relies on the browser's confirm() API, that is kinda ugly.

Check out this gem that politely hooks into the Rails' UJS adapter (via the confirm event) and builds a twitter bootstrap modal out of the data- elements of the link. Feedback welcome!

@noorani786
Copy link

Why not just use Bootstrap's modal functionality to pop open the confirm and also to grab the id?

<a href="#delete-confirm" data-target="delete-confirm-modal" data-id="<%= @something.id %>" class="delete-confirm btn btn-danger"><i class="icon-trash icon-white"></i></a>

And then do:

$('#delete-confirm').on('show.bs.modal', function(event) {
 var id = $(event.relatedTarget).data('id')
  var $submit = $(this).find('.btn-danger'),
      href = $submit.attr('href');
  $submit.attr('href', href.replace('pony', id));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment