scientiffic
scientiffic

Reputation: 9415

determine if user selects 'cancel' in dialog box

In my rails app, I create a confirm dialog when a user tries to delete an image:

<%= link_to image, :method => :delete, :confirm=> "Are you sure you want to delete this video?", :remote => true, :class=> "btn btn-mini trash" do %>
   <i class="icon-trash"></i>
<% end %>

How can I detect, with jquery, if the user selects 'cancel' from the dialog window?

Upvotes: 2

Views: 100

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Graham provides nice link to Steve's article.

So, based on the article and UJS code, you can overwrite UJS's confirm method.

The original code is simple(https://github.com/rails/jquery-ujs/blob/master/src/rails.js)

// Default confirm dialog, may be overridden with custom 
// confirm dialog in $.rails.confirm
confirm: function(message) {
  return confirm(message);
},

Then, using vanilla Javascript you can write something like this in your app's js file to override this method.

$.rails.confirm = function(message) {
  if (confirm(message)) {
    return true;            //UJS will continue doing his job
  } else {         
    console.log('canceled') // Do you own logic
    return false;           //Make sure to return false at the end
  }     
}

jsfiddle demo: http://jsfiddle.net/billychan/GS5hZ/

Upvotes: 2

Graham Conzett
Graham Conzett

Reputation: 8454

This functionality is based on Rails' UJS library, which you can customize pretty easily to suite your needs, even doing completely custom dialog boxes based on Twitter Bootstrap or other UI toolkits. There are several resources for doing so. Here is a good post on this, as well as this Stack Overflow post.

Upvotes: 0

Related Questions