我有一个表单,我想在点击提交按钮后显示确认消息,而且我不想使用以下方法
return confirm("Are You Sure?")
我用了JQuery Confirm如下。
@using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
javascript 代码是...
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 Confirm )是
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();
}
}
});
}
问题是……
当我单击“提交”按钮时,它不会等待我单击“确认”框中的"is"按钮并且表单将提交(“确认”框出现并在 1 秒后消失并提交表单)。
但是当我使用 alert("For Test"); 而不是 $("#ReceptionForm").submit(); 时,它工作正常。有谁知道我为什么会遇到这个问题?!!!
最佳答案
您可以使用“标志”来了解是否对 "prevent default" 进行了确认。提交行为。
删除内联 onsubmit = "ValidateMyform(this);"
并改用 jQuery 事件处理程序。
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();
}
}
});
}
});
关于javascript - 如何在使用 jquery 确认提交表单之前显示确认框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46020520/