overriding the window.confirm dialog 08 Feb 2012
Tags: javascript

I need to use jQuery Dialog for confirming if a user wants to do a certain action or not. So a link_to with a :confirm attribute will use jquery instead of the browser confirm prompt.

This is the final code (each section will be explained later).

javascript
var dialogOptions = {
  autoOpen: false,
  modal: true,
  draggable: false,
  resizable: false,
  width: 500, 
  show: 'fold',
  hide: 'fold',
  buttons: {
    "Yes": function() {currentLink.attr('data-answer', 'yes').trigger('click');$(this).dialog('close')},
    "No": function() {$(this).dialog('close')}
  }
}

$('#global-confirm-dialog').dialog(dialogOptions);

$('a[data-confirm]').click(function(event) {
  currentLink = $(this);
  var dialog = $('#global-confirm-dialog');

  if (currentLink.attr('data-answer') != 'yes') {
    event.stopImmediatePropagation();
    dialog.children('.question').text(currentLink.attr('data-confirm'));
    dialog.dialog('open')
    event.preventDefault();
  }

  currentLink.attr('data-answer', 'no');
});