19

I am using jQuery UI dialog to display a confirmation dialog when a button is clicked. I want to return true, when OK is clicked and false otherwise.

Associating dialog open call in onClick (as given here, $dialog.dialog('open');) event does not serve the purpose. So, as a workaround, I followed an approach, which is similar to this: http://www.perfectline.co.uk/blog/unobtrusive-custom-confirmation-dialogs-with-jquery. There are two differences between this approach and mine:

  1. The example uses anchor tag and,
  2. It does not use jQuery UI dialog.

I have modified the code given in the example link, but it does not work. I wonder what I am doing wrong. Is there any cheaper way to do this?

Here is the code, all the CSS/JS are referencing to jQuery CDN, so you should be able to copy the code to see the behavior.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/themes/blitzer/jquery-ui.css" rel="stylesheet" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Control Panel</title>
  </head>

  <body>
    <form action="http://google.com">
      <button class="es-button ui-state-default ui-corner-all" name="changeSem" id="id2">Start Thermonuclear War</span>
      </button>
    </form>
    <div title="Why so serious?" id="id3" style="display:none;">
      <p>You are about to start a war.
        <p>Click OK to confirm. Click Cancel to cancel this action.</p>
    </div>
  </body>
  <script type="text/javascript">
    $('#id2').click(function (event) {

      if ($(this).data('propagationStopped')) {
        //alert('true');
        $(this).data('propagationStopped', false);
        return true;
      } else {

        event.stopImmediatePropagation();

        $('#id3').dialog({
          //autoOpen: false,
          width: 600,
          buttons: {
            "Ok": function () {
              $(this).dialog("close");
              $('#id2').data('propagationStopped', true);
              $('#id2').triggerHandler(event);
            },
            "Cancel": function () {
              $(this).dialog("close");
              return false;
            }
          }
        });
        //alert('false');
        return false;
      }
    });
  </script>

</html>

Clarification: Please note that it's very simple (see the solution by bryan.taylor) to do a form submission. What I want to do here is to simulate submission by button click. More like JavaScript's confirm() method.

Community
  • 1
  • 1
Nishant
  • 54,584
  • 13
  • 112
  • 127
  • Ideally, this example should take you to Google on OK and close and do nothing on Cancel. I would try to avoid explicit $(formName).submit() based solution. – Nishant Aug 24 '10 at 21:02
  • possible duplicate of [jquery ui dialog box need to return value, when user presses button, but not working](http://stackoverflow.com/questions/6049687/jquery-ui-dialog-box-need-to-return-value-when-user-presses-button-but-not-wor) – Liam Aug 20 '13 at 13:28

2 Answers2

49

JavaScript is asynchronous. The call to

$myDialog.dialog('open'); 

will not block, but rather will return immediately.

Instead, one must use event callbacks that you provide in the buttons option of dialog.

This near-duplicate provides a good example:

jquery ui dialog box need to return value, when user presses button, but not working

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
8

Your code is a bit convoluted, I think there is a much easier way to do this. You should instantiate the dialog first, then open it on the click event for your button. Code would look similar to this:

<script>
$(document).ready(function () {
  var $myDialog = $('<div></div>')
    .html('You are about to start a war.<br/>Click OK to confirm.  Click Cancel to stop this action.')
    .dialog({
    autoOpen: false,
    title: 'Why so serious?',
    buttons: {
      "OK": function () {
        $(this).dialog("close");
        window.open('http://google.com/');
        return true;
      },
      "Cancel": function () {
        $(this).dialog("close");
        return false;
      }
    }
  });

  $('#myOpener').click(function () {
    return $myDialog.dialog('open'); //replace the div id with the id of the button/form
  });
});
</script>

<div id="myOpener"></div>

Here is the jQuery UI Dialog API documentation, so you can see all your options:

http://api.jqueryui.com/dialog/

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
bryan.taylor
  • 584
  • 2
  • 9
  • PS I didn't test this code, just pretty much wrote it so you could have an idea of how to approach this issue, so there might be some minor tweaks needed. – bryan.taylor Aug 24 '10 at 21:26
  • Yeah, this code is alright. The only thing is I want to submit a form.. so what I will do is put $('#formId').submit() inplace of window.open('http://google.com/'); in your answer. But the issue is I want to simulate submission by button click. I realized perhaps the question was not clear, I am adding clarification in the question. Thanks for suggestion. – Nishant Aug 24 '10 at 23:09
  • @Nishant: Not really sure what you mean by 'simulate submission by button click'. Do you mean that you want to stop the submit event from taking place when someone clicks OK? I guess I'm just asking for you to elaborate on what 'simulate submission' means, can you provide a relevant use case? – bryan.taylor Aug 24 '10 at 23:15
  • I mean functionality same as . where onClick event gets either true or false based on what user clicked in confirmation dialog. – Nishant Aug 24 '10 at 23:20
  • Ah ok now I understand, that's very easy. All you need to do is change the inside two lines of this function: $('#myOpener').click(function(){ $myDialog.dialog('open'); //prevents default link follow action return false }); to: return $myDialog.dialog('open'); and the click event should return the result of the button press. I'll edit the code above to be correct so you can see. – bryan.taylor Aug 24 '10 at 23:23
  • 8
    No, actually. $myDialog.dialog('open'); just displays the confirmation div and returns true. While JavaScript confirm function waits for user's response and returns boolean based on what user clicked. Your solution would show a dialog box and immediately submit. And that's the reason, I went through the harder route of capturing click event propagation and then restarting the event using triggerHandler. – Nishant Aug 25 '10 at 07:00
  • Did you get this to work properly? I have validation processes that need to run after a return true - var where_to_coupon = confirm(pm_info_msg_013); if (where_to_coupon== true) { doSubmit=true; return doSubmit; – Jason Aug 10 '11 at 19:24
  • 4
    This accepted solution is wrong. See my answer for a correct solution. – Eric J. Sep 18 '12 at 15:41
  • @Nishant: Since this is *your* question, you should not accept an incorrect solution. – Eric J. Oct 11 '12 at 20:36