theDmi theDmi - 19 days ago 9
jQuery Question

Confirm form submission using bootbox.confirm()

I have a form and want to intercept form submission to display a confirmation dialog using bootbox.


  1. User enters some data

  2. User hits submit

  3. A confirmation dialog is shown



If the user hits
OK
, then the form should submit, if not it should just stay on the page.

I tried this:

$('#myForm').submit(function() {
return bootbox.confirm("Are you sure?");
});


However,
bootbox.confirm()
immediately returns, the confirmation dialog is hidden again.

I then noticed that there is a callback parameter on
bootbox.confirm()
. However, if I'm to call
$('#myForm').submit()
from the callback, this will obviously just show the confirmation dialog again.

So what is the proper way to confirm form submission?

Answer

I only got this working by preventing the default form behaviour, here is the solution below. I'm using this in a list of forms, each one with a submit delete button and it works fine.

<script type="text/javascript">
    $('form').submit(function(e) {
        var currentForm = this;
        e.preventDefault();
        bootbox.confirm("Are you sure?", function(result) {
            if (result) {
                currentForm.submit();
            }
        });
    });
</script>
Comments