在使用jquery确认提交表单之前,如何显示确认框?
我有一个表格,我想在单击提交"按钮后显示确认消息,并且我也不想使用以下方法
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?")
我使用了 JQuery确认,如下所示.
@using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
javascript代码是...
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;
}
用于显示确认框的Javascript代码(根据 JQuery确认)是
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();
}
}
});
}
问题在...
当我单击提交"按钮时,它不会等我单击确认"框中的是"按钮,表单将提交(出现确认"框,一秒钟后消失并提交表单).
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).
但是当我使用 alert("For Test"); 而不是 $(#ReceptionForm").submit(); 时,它可以正常工作.有人知道我为什么要面对这个问题吗?!!
But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!
您可以使用标志"来知道是否进行了确认,"防止默认值"提交行为.
You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.
删除内联 onsubmit ="ValidateMyform(this);"
并改用jQuery事件处理程序.
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();
}
}
});
}
});