JonoB
JonoB

Reputation: 5887

Jquery modal dialog and form submit

I have a form where I need to display a confirm dialog to the user before saving.

I have done this by intercepting the form submit function as follows:

$("#my_form").submit(function(e) {
    if ($("#id").val() > 0) {
        var $dialog = $('<div></div>')
            .html('Are you sure?')
            .dialog({
                autoOpen: false,
                title: 'Save New Invoice',
                modal: true,
                buttons: {
                    "OK": function() {
                        $dialog.dialog('close');
                        $("#my_form").submit();
                    },
                    Cancel: function() {
                        $(this).dialog("close");            
                    }
                }
            });
        $dialog.dialog('open');
        e.preventDefault();
        return false;
    }       
});

However, the OK button does not function correctly - the dialog does not close and the form is not submitted.

If I change the OK function as follows, then the dialog is closed and the alert is shown.

"OK": function() {
  $dialog.dialog('close');
  alert('form will be submitted');
},

So, I am guessing that this is something to do with the $("#my_form").submit(); method.

Upvotes: 1

Views: 5051

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The problem you've got is that your submit handler always returns false and has e.preventDefault() too for good measure. Both of these will stop the form being submitted, regardless of whether the user clicked OK or Cancel.

You need to change the logic so that your modal confirmation is shown on a button click (or any other event), not on the form submission. Then, if the user clicks ok you can call the forms' submit() method.

$("#submitButton").click(function(e) {
    if ($("#id").val() > 0) {
        var $dialog = $('<div></div>')
            .html('Are you sure?')
            .dialog({
                autoOpen: false,
                title: 'Save New Invoice',
                modal: true,
                buttons: {
                    "OK": function() {
                        $dialog.dialog('close');
                        $("#my_form").submit();
                    },
                    Cancel: function() {
                        $(this).dialog("close");            
                    }
                }
            });
        $dialog.dialog('open');
    }       
});

Upvotes: 0

Rohith Nair
Rohith Nair

Reputation: 1070

Isn't this like calling your form submit function again and again. I see you are attaching the function to submit functionality, and when you call the submit again,it is invoking the same function.

Your $("#invoice_edit_form") is some other form.Is it like asking one form to submit other form?

Upvotes: 2

Related Questions