1

I have a simple form:

<form id="cancel" method="post" action="/Controller/Cancel">
   <input class="submitbtn" type="submit" value="Go">
   ...

I'm using jQuery with a jQuery UI dialog. What I'd like to do is hijack the submit of the form and display a dialog. When the user clicks 'yes' in the dialog, the form carries on and does a normal page submit. If they click 'No', the dialog just cancels.

I have this code:

$(document).ready(function () {

$("#dialog").dialog({
    resizable: false,
    autoOpen: false,
    modal: true,
    buttons: {
        "Yes": function () {
            // Not sure what to do here
            $(this).dialog("close");
        },
        "No": function () {
            $(this).dialog("close");
        }
    }
});

$('#cancel').submit(function (event) {
    event.preventDefault();
    $('#dialog').dialog('open');

});

}); 

My question is, how do I get the submit code to return true/false to the client based on the response from the dialog.

Any help appreciated.

animuson
  • 53,861
  • 28
  • 137
  • 147
Matt
  • 5,573
  • 4
  • 33
  • 37
  • 1
    I won't post that as an answer, but do know you can do it without the use of jQuery with JavaScript `confirm()` function, it returns whether `true` or `false` depending on the user's input in the GUI, so you could just do `areYouSure = confirm("Are you sure?"); return areYouSure;` – Madara's Ghost Sep 05 '11 at 18:15

2 Answers2

1

The problem here is that when you use $('#cancel').submit() within the "Yes" button callback, the submit event is triggered again and event.preventDefault() stops the from from actually being submitted.

A quick fix would be to unbind your submit event just before actually submitting the form. (Demo: http://jsfiddle.net/WQjFj/6/)

$("#dialog").dialog({
    resizable: false,
    autoOpen: false,
    modal: true,
    buttons: {
        "Yes": function() {
            $('#cancel').unbind("submit").submit();
            $(this).dialog("close");
        },
        "No": function() {
            $(this).dialog("close");
        }
    }
});

Another solution can be found on this answer: Using jquery ui dialog to confirm action for form submission

Community
  • 1
  • 1
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
  • Thanks. The demo on jsfiddle was very helpful. Not seen that site before - will use it again! – Matt Sep 06 '11 at 08:04
0

You could submit the form directly from the dialog. Where you have //Not sure what to do here, put

$("#cancel").submit();

Here's a guide you may have seen:

http://www.jensbits.com/2009/08/10/modal-confirmation-dialog-on-form-submit-javascript-jquery-ui-and-thickbox-varieties/

spike
  • 9,794
  • 9
  • 54
  • 85