I have a form and want to intercept form submission to display a confirmation dialog using bootbox.
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?
js is a small JavaScript library which allows you to create programmatic dialog boxes using Bootstrap modals, without having to worry about creating, managing, or removing any of the required DOM elements or JavaScript event handlers.
Pressing the ESC key or clicking close () dismisses the dialog and invokes the callback as if the user had clicked the Cancel button. Confirm dialogs require a callback function.
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>
As always: Just after you ask a question, you find the answer yourself :-) . See this answer: https://stackoverflow.com/a/2420806/219187 (also note the comment in the answer).
Adapted to my problem, the solution looks as follows:
$('#myForm').submit(function() {
var currentForm = this;
bootbox.confirm("Are you sure?", function(result) {
if (result) {
currentForm.submit();
}
});
});
This code works perfectly for me...
<script type="text/javascript">
$('#myForm').click(function(e) {
e.preventDefault();
var msg = 'Souhaitez vous vraiment supprimer ce produit ?';
bootbox.confirm(msg, function(result) {
if (result) {
$('#myForm').submit();
}
});
});
</script>
You can a solve this by passing additional parameters to your submit handler using the .trigger() method:
$('form').submit(function (e, confirmed) {
var currentForm = $(e.currentTarget);
if (!confirmed) {
e.preventDefault();
bootbox.confirm("Are you sure?", function (result) {
if (result) {
currentForm.trigger('submit', { confirmed: true });
}
});
}
});
When the form is first submitted, the 'confirmed' parameter is undefined and the bootbox dialog is displayed. If the user confirms the action in the dialog, submit event is triggered again with the additional parameter and the form is submitted normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With