问题描述
如果验证失败,我试图阻止我的表单提交.我尝试关注此上一篇文章,但对我不起作用.我错过了什么?
I'm trying to stop my form from submitting if a validation fails. I tried following this previous post but I doesn't work for me. What am I missing?
<input id="saveButton" type="submit" value="Save" />
<input id="cancelButton" type="button" value="Cancel" />
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function (e) {
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data, e);
},
cache: false
});
});
});
$("#cancelButton").click(function () {
window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
$(this).select();
});
function showMsg(hasCurrentJob, sender) {
if (hasCurrentJob == "True") {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
if (sender != null) {
sender.preventDefault();
}
return false;
}
}
</script>
推荐答案
同样,AJAX 是异步的.所以showMsg函数只有在服务器响应成功后才会调用..表单提交事件不会等到AJAX成功.
Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.
将 e.preventDefault();
作为点击处理程序的第一行.
Move the e.preventDefault();
as first line in the click handler.
$("form").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...
见下面的代码,
我希望它被允许 HasJobInProgress == False
I want it to be allowed HasJobInProgress == False
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
$.ajax({
url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
data: { id: '@Model.ClientId' },
success: function (data) {
showMsg(data);
},
cache: false
});
});
});
$("#cancelButton").click(function () {
window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
$(this).select();
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob == "True") {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
return false;
} else {
$("form").unbind('submit').submit();
}
}
这篇关于停止提交表单,使用 Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2