I\'m trying to confirm a submit form that is created using ruby on rails, but before submitting I have a condition that open a confirm popup asking if the user really wants
The issue is in the way that the browser handles it's own alert, confirm, and prompt versus self generated dialogs. You need to add in a try/catch sort of scenario.
I created the following a bit back to address this: https://jsfiddle.net/Twisty/7kp46r22/3/
This uses $.Deferred
and $when()
to wait for the user to make a selection before returning the results or executing any callbacks.
For your application, this might look like:
Working example: https://jsfiddle.net/Twisty/wtogu9cu/
HTML
<form id="myForm">
Submit Form:
<button type="submit">Go</button>
</form>
jQuery
function ui_confirm(message, callback) {
var dfd = $.Deferred();
var dialog = $("<div>", {
id: "confirm"
})
.html(message)
.appendTo($("body"))
.data("selection", false)
.dialog({
autoOpen: false,
resizable: false,
title: 'Confirm',
zIndex: 99999999,
modal: true,
buttons: [{
text: "Yes",
click: function() {
$(this).dialog("close");
dfd.resolve(true);
if ($.isFunction(callback)) {
callback.apply();
}
}
}, {
text: "No",
click: function() {
$(this).dialog("close");
dfd.resolve(false);
}
}],
close: function(event, ui) {
$('#confirm').remove();
}
});
dialog.dialog("open");
return dfd.promise();
}
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
// your code
$.when(ui_confirm("Are you sure?")).done(function(val) {
if (val) {
console.log("Submit the form.");
$('#myForm')[0].submit();
} else {
console.log("Do not submit the form.");
}
});
});
});