Rails UJS confirm box cancel button callback
Asked Answered
H

2

7

I am using Rails jquery ujs for handling ajax within my app. Also I am using a the confirm option for destroying any records. As my current setup, I have hooked up a loading overlay screen on click of data-remote=true link.

All I wanted to know is: Is there a way I can hook a callback event when a user clicks cancel on the confirm box and I can close the loader overlay.

Hypochromia answered 22/10, 2013 at 11:31 Comment(1)
I don't know and don't think this is something worth research. "Cancel" is "cancel". It should not have any side effect. What you are going to do breaks usability.Doubtless
W
7

Yes, you can. Pass in the response object. In CoffeeScript.

  $('selector').on 'confirm:complete', (e, response) ->
    if response
      # User confirmed
    else
      # User cancelled.

In Javascript:

  $('selector').on('confirm:complete', function(e, response) {
    if(response) {
      // User confirmed
    }
    else {
      // User cancelled.
    }
  });
Warrenwarrener answered 11/2, 2014 at 10:26 Comment(1)
@ArupRakshit It's a custom event from Rails UJS. See github.com/rails/jquery-ujs/blob/master/src/rails.js#L280Warrenwarrener
C
4

For those of you stumbling on this question and using Rails >= 5.1, note that the callback parameters have been bundled into event.detail, which is an array. The first callback parameter is event.detail[0] and so on.

To update Mohamad's answer, here's how to check the confirm value in Rails >= 5.1.

$('selector').on('confirm:complete', function(e) {
  if (e.detail[0]) {
    // User confirmed
  }
  else {
    // User cancelled.
  }
});

From Rails Guide:

Rails 5.1 introduced rails-ujs and dropped jQuery as a dependency. [...] Unlike the version with jQuery, all custom events return only one parameter: event. In this parameter, there is an additional attribute detail which contains an array of extra parameters.

Courtyard answered 19/2, 2019 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.