Reputation: 55
I have a form and I want to show a confirmation massage after clicking submit button and also I don't want to use following method
return confirm("Are You Sure?")
I used JQuery Confirm as following.
@using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
The javascript codes are ...
function ValidateMyform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].hasAttribute("required")) {
if (inputs[i].value == "") {
// found an empty field that is required
alert("Fill all fields");
return false;
}
}
}
return true;
}
The Javascript code for showing Confirm Box (According JQuery Confirm) is
function SubmitMyForm() {
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return true;
},
Yes: function () {
$("#ReceptionForm").submit();
//alert("For Test");
//document.getElementById("ReceptionForm").submit();
}
}
});
}
The Problem IS...
When I click Submit button it doesn't wait for me to click Yes button in Confirm box and the form will submit (the Confirm box appears and after 1 sec disappear and form submits).
But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!
Upvotes: 1
Views: 3505
Reputation: 33933
You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.
Remove the inline onsubmit = "ValidateMyform(this);"
and use a jQuery event handler instead.
var confirmed = false;
$("#ReceptionForm").on("submit", function(e){
// if confirm == true here
// And if the form is valid...
// the event won't be prevented and the confirm won't show.
if(!confirmed && ValidateMyform($(this)[0]) ){
e.preventDefault();
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return;
},
Yes: function () {
confirmed = true;
$("#ReceptionForm").submit();
}
}
});
}
});
Upvotes: 2