我的MVC应用中有很多页面,用户点击“提交”按钮发布表单。有时用户会单击“提交”,因为没有立即发生,请再次单击它。因此,表单提交两次。为了防止这种情况,我有以下JavaScript代码:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
此代码禁用“提交”按钮,因此用户无法单击两次。这很好用。但是,如果表单上存在客户端验证错误,则“提交”按钮将被禁用,但表单永远不会发布,现在用户无法发布表单。我可以对JS代码进行更改,以检测是否存在客户端验证错误,如果有,我要么不要禁用“提交”按钮,要么重新启用它?
答案 0 :(得分:3)
如果您正在使用jQuery Validate,您可以在禁用按钮之前检查表单是否有效:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
答案 1 :(得分:0)
您可以尝试这样的事情:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
使用Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
答案 2 :(得分:-1)
切换它。
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});