How to implement "confirmation" dialog in Jquery UI dialog?

xandy picture xandy · May 20, 2009 · Viewed 332.1k times · Source

I am try to use JQuery UI Dialog to replace the ugly javascript:alert() box. In my scenario, I have a list of items, and next to each individual of them, I would have a "delete" button for each of them. the psuedo html setup will be something follows:

<ul>
    <li>ITEM <a href="url/to/remove"> <span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
</ul>

<div id="confirmDialog">Are you sure?</div>

In JQ part, on document ready, I would first setup the div to be a modal dialog with necessary button, and set those "a" to be firing to confirmation before to remove, like:

$("ul li a").click(function() {
  // Show the dialog    
  return false; // to prevent the browser actually following the links!
}

OK, here's the problem. during the init time, the dialog will have no idea who (item) will fire it up, and also the item id (!). How can I setup the behavior of those confirmation buttons in order to, if the user still choose YES, it will follow the link to remove it?

Answer

Paul Morie picture Paul Morie · Jun 10, 2009

I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click. I used a CSS class to indicate which links should have the confirmation behavior.

Here's my solution, abstracted away to be suitable for an example.

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });
  });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });
</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

I believe that this would work for you, if you can generate your links with the CSS class (confirmLink, in my example).

Here is a jsfiddle with the code in it.

In the interest of full disclosure, I'll note that I spent a few minutes on this particular problem and I provided a similar answer to this question, which was also without an accepted answer at the time.